public class Demo2 {
private volatile static Object lock = new Object();
private static volatile int o = 0;
private static volatile int count;
private static AtomicInteger a = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new R(), "t1");
t1.start();
Thread t2 = new Thread(new R(), "t2");
t2.start();
t1.join();
t2.join();
System.out.println("==========main==========");
}
static class R implements Runnable {
@Override
public void run() {
while (true && count < 10) {
count++;
synchronized (lock) {
System.out.print(Thread.currentThread().getName() + ":");
System.out.println(++o);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notify();
if(o!=10){
try {
//满10个唤醒其他线程
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
System.out.println(Thread.currentThread().getName() + "end"+count);
}
}
}
结果如下: