微科社区,轻松开发从此开始! 请登陆 免费注册

微科社区

当前位置:首页 > Java平台 > 多线程编程 >

java-线程-线程同步通信技术

时间:2017-01-20 04:01  浏览:努力统计中...
源代码如下 01public 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

源代码如下
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             public void 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(int i){
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 void main(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              

顶一下
(0)
0%
踩一下
(0)
0%
------分隔线------
栏目列表
推荐内容