源代码如下
01 public class TranditionalThreadCommunication {
02
03 /**
04 * @param args
05 */
06 public static void main(String[] args) {
07 final Business business =new Business();
08
09
10 new Thread(new Runnable() {
11 @Override
12 publicvoid run() {
13
14 for(int i = 0; i<50;i++){
15 business.sub(i);
16 }
17 }
18 }).start();
19
20 for(int i = 0; i < 50;i++){
21 business.main(i);
22 }
23 }
24 }
25
26 /**
27 * 这个类是线程同步的
28 * @author gavinlin
29 *
30 */
31 class Business{
32 private boolean bShouldSub =true;
33
34 public synchronized void sub(inti){
35 while(bShouldSub){
36 try {
37 this.wait();
38 } catch (InterruptedException e) {
39 // TODO Auto-generated catch block
40 e.printStackTrace();
41 }
42 }
43
44 for(int j=0;j<10;j++){
45 System.out.println("subThread" + j +"loop " + i);
46 }
47 bShouldSub = !bShouldSub;
48 this.notify();
49 }
50
51 public synchronized voidmain(int i){
52 while(!bShouldSub){
53 try {
54 this.wait();
55 } catch (InterruptedException e) {
56 // TODO Auto-generated catch block
57 e.printStackTrace();
58 }
59 }
60
61 for(int j=0;j<100;j++){
62 System.out.println("mainThread" + j + "loop " + i);
63 }
64 bShouldSub = !bShouldSub;
65 this.notify();
66 }
67 }
上面的代码干了什么?
1.主要看main方法,生成了一个Business类的对象(先不管business里是干什么用的),然后开一个线程,循环50次调用business.sub,主线程也循环50次调用business.main
2.看看business里面实现了什么,sub方法就是重复10次打印信息,main方法重复100次调用打印信息。两个方法都做了同步,bShouldSub判断是否该运行方法,wait方法和notify方法是这里的重点,作用是如果该方法不该运行就阻塞(运行wait),方法运行完调用notify(通知正在wait的方法可以往下执行了)。
3.根据1和2,可以得出其运行结果是调用同一个business时sub打印10次信息,再到main打印100次信息,重复上述步骤50次
QQ 744437114
疯狂软件官网:http://www.fkjava.org
疯狂java视频 android视频:http://www.fkjava.org/video.html |
|