- 主要使用同步锁和notifyall(),wait()
- 注意逻辑顺序,先唤醒其他线程,再释放锁
public class TurningTest {
private int count =0;
private final Object lock = new Object();
public static void main(String[] args) {
new TurningTest().foo();
}
public void foo(){
new Thread(new myRun(),"偶线程").start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new myRun(),"奇线程").start();
}
class myRun implements Runnable{
@Override
public void run(){
while (count<=100){
synchronized (lock){
System.out.println(Thread.currentThread().getName()+": "+count);
count++;
lock.notifyAll();
try {
if(count<=100){
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
网友评论