public class Test {
static volatile int count = 1;
final static Object obj = new Object();
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();
t2.start();
}
static class MyRunnable implements Runnable{
public void run() {
try {
synchronized (obj){
while(count <= 100){
System.out.println(Thread.currentThread().getName()+":"+count++);
obj.notifyAll();
if(count < 100){
obj.wait();
}
}
}
System.out.println("done");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
用一个volatile变量,实现可见性,两个Thread各自实现打印效果,用wait作等待,用notifyAll进行唤醒。
if(count < 100){
obj.wait();
}
之所以加这个判断,是为了让线程结束最后的等待状态。要不然两个线程中的一个最后始终处于等待状态