zoukankan      html  css  js  c++  java
  • 一个关于java线程的面试题

    闲着没事干,在网上看一些面试题,找到一个比较经典的面试题,自己动手写了写。

    题目: 子线程循环10次, 接着主线程循环100次, 接着子线程再循环10次, 接着主线程再循环100次,如此循环50次, 请写出程序 !

    于是我自己研究了一下写了如下代码,也许还不是很完美吧,自我认为已经差不多了。

    代码如下
     1 public class ThreadQuestion {
    2 public static void main(String[] args) {
    3 new ThreadQuestion().init();
    4 }
    5
    6 private void init(){
    7 final Business business=new Business();
    8 new Thread(new Runnable() {
    9 public void run() {
    10 for (int i = 1; i <=50 ; i++) {
    11 business.sub(i);
    12 }
    13 }
    14 }).start();
    15
    16 for (int i = 1; i <=50 ; i++) {
    17 business.main(i);
    18 }
    19 }
    20
    21 class Business{
    22 boolean subDone=true;
    23 public synchronized void sub(int i){
    24 while(!subDone){
    25 try {
    26 this.wait();
    27 } catch (InterruptedException e) {
    28 e.printStackTrace();
    29 }
    30 }
    31 for (int j = 1; j <=10; j++) {
    32 System.out.println("子线程循环第"+j+"次 第"+i+"次循环");
    33 }
    34 subDone=false;
    35 this.notify();
    36 }
    37 public synchronized void main(int i){
    38 while(subDone){
    39 try {
    40 this.wait();
    41 } catch (InterruptedException e) {
    42 e.printStackTrace();
    43 }
    44 }
    45 for (int j = 1; j <=100; j++) {
    46 System.out.println("主线程循环第"+j+"次 第"+i+"次循环");
    47 }
    48
    49 subDone=true;
    50 this.notify();
    51 }
    52 }
    53 }


     

  • 相关阅读:
    Java计算某个日期是一年中的第几天
    k8s-CentOs7.x 搭建集群(1)(kubelet 1.19.2)
    k8s-PV、PVC(7)
    k8s-Volumes(6)
    k8s-Scale、Rolling Update(5)
    k8s-Service介绍(4)
    k8s-部署AspNetCore应用(3)
    k8s-搭建Dashboard(2)
    AspNetcore搭配Serilog利用docker发布CentOs7
    CentOs7 搭建http服务器访问文件目录
  • 原文地址:https://www.cnblogs.com/Laupaul/p/2371883.html
Copyright © 2011-2022 走看看