public class PrintNumber {
private static volatile int i = 0;
public static void main(String[] args) throws Exception {
final Object obj = new Object();
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (obj) {
for (; i < 100; ) {
System.out.println(Thread.currentThread().getName() + " " + (i++));
try {
obj.notifyAll();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notifyAll();
}
}
};
Thread t1 = new Thread(runnable, "线程1 ");
Thread t2 = new Thread(runnable, "线程2 ");
t2.start();
t1.start();
}
}
网友评论