package threadcoreknowledge.createthreads;
public class PrintTest {
private static int count ;
private static final Object lock = new Object();
public static void main(String[] args){
// int count = 0;
// Object lock = new Object();
System.out.println("start---");
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
while (count<100){
if ((count & 1) == 0){
System.out.println(Thread.currentThread().getName()+":"+ count++);
waitNotify();
}
}
}
}
}, "偶数").start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock){
while (count<100){
if ((count & 1) == 1){
System.out.println(Thread.currentThread().getName()+":"+count++);
waitNotify();
}
}
}
}
}, "基数").start();
}
public static void waitNotify(){
lock.notifyAll();
if (count<100){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
需要把count放到共享代码块中,