赞
踩
public class SortThread {
private Lock lock;
private Condition conditionA;
private Condition conditionB;
public SortThread(Lock lock, Condition conditionA, Condition conditionB) {
super();
this.lock = lock;
this.conditionA = conditionA;
this.conditionB = conditionB;
}
private class ThreadA extends Thread{
@Override
public void run() {
super.run();
while(true){
lock.lock();
System.out.println("ThreadA--run");
try {
conditionB.signal();//唤醒B
TimeUnit.SECONDS.sleep(1);
conditionA.await();//使当前线程处于Waiting状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private class ThreadB extends Thread{
@Override
public void run() {
while(true){
lock.lock();
System.out.println("ThreadB--run");
try {
conditionA.signal();//唤醒A
TimeUnit.SECONDS.sleep(1);
conditionB.await();//使当前线程处于Waiting状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
SortThread st = new SortThread(lock,conditionA,conditionB);
ThreadA ta = st.new ThreadA();
ThreadB tb = st.new ThreadB();
ta.start();
tb.start();
}
}
注意:一定要先执行signal(),若先执行了await(),程序会直接挂起,即直接进入waiting状态,不会继续往下执行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。