package test1;
public class test3 {
private static volatile int i = 1;
public static class Test implements Runnable{
final Object obj = new Object();
@Override
public void run() {
synchronized (obj) {
for (; i < 10; ) {
System.out.println(Thread.currentThread().getName() + " " + (i++));
try {
obj.notifyAll();
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
obj.notifyAll();
}
}
}
public static void main(String[] args) throws Exception {
Test runnable=new Test();
Thread t1 = new Thread(runnable, "打印偶数的线程 ");
Thread t2 = new Thread(runnable, "打印奇数的线程 ");
t2.start();
t1.start();
}
}
经典面试题——两个线程交替打印奇数和偶数
最新推荐文章于 2022-04-21 20:12:25 发布