一个关于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 }


 

原文地址:https://www.cnblogs.com/Laupaul/p/2371883.html