本帖最后由 降魔神兵 于 2016-8-2 23:58 编辑
观看了 创制博客的里面 java多线程视频
http://dvd.boxuegu.com/course/37.html
第13节 - 13_java5条件阻塞Condition的应用
当三个线程之间通信的时候 视频中 用了3个 condition
我个人研究下 用了 2个 condition 发现也可以,
所以请各位黑马帮我看看 是否 正确?
代码如下
[Java] 纯文本查看 复制代码 public class ThreeConditionCommunication2 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final Business bus=new ThreeConditionCommunication2().new Business();
new Thread(
new Runnable(){
@Override
public void run() {
for (int j = 0; j < 5; j++) {
bus.sub2(j);
}
}
}
).start();
new Thread(
new Runnable(){
@Override
public void run() {
for (int j = 0; j < 5; j++) {
bus.sub3(j);
}
}
}
).start();
for (int j = 0; j < 5; j++) {
bus.sub1(j);
}
}
//主要是这里不同
class Business{
Lock lock=new ReentrantLock();
Condition con1=lock.newCondition(); // 1 - 2 通信
Condition con2=lock.newCondition(); // 2 - 3 通信
int step=1;
public void sub1(int i){
lock.lock();
try {
while(step!=1)
con1.await();
for (int j = 0; j < 100; j++) {
System.out.println("main thread sequence of "+j+" loop of"+i);
}
step=2;
con1.signal();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void sub2(int i){
lock.lock();
try {
while(step!=2)
con1.await();
for (int j = 0; j < 10; j++) {
System.out.println("Sub2 thread sequence of "+j+" loop of"+i);
}
step=3;
con2.signal();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void sub3(int i){
lock.lock();
try {
while(step!=3)
con2.await();
for (int j = 0; j < 20; j++) {
System.out.println("Sub3 thread sequence of "+j+" loop of"+i);
}
step=1;
con1.signal();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
}
|