码迷,mamicode.com
首页 > 编程语言 > 详细

线程互斥通信

时间:2016-03-09 00:00:53      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

1.子线程运行10次,主线程运行20次,接着回到子线程10次,然后在是主线程20次,如此循环10次。

** 当要用到共同数据(包括同步锁)的若干方法应当放在同一个类当中,体现了程序的高类聚,和健壮性。
public class Test{
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
public void run() {
for(int i=1;i<=10;i++){
business.son();
}
}
}).start();

for(int i=1;i<=10;i++){
business.main();
}
}
}

class Business{
boolean b = true;
public synchronized void son(){
while(!b){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for(int j = 1;j<=10;j++){
System.out.println("son=>"+j);
}

b = false;
this.notify();
}

public synchronized void main(){
while (b) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

for(int j = 1;j<=20;j++){
System.out.println("main=>"+j);
}

b = true;
this.notify();
}
}

技术分享

线程互斥通信

标签:

原文地址:http://www.cnblogs.com/dsking/p/5256281.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!