public class AlternatePrintingTest implements Runnable {
int num = 1;
static Object lock = new Object();
@Override
public void run() {
synchronized (lock) {
while (true) {
lock.notify();
if (num <= 100) {
System.out.println(Thread.currentThread().getName() + "num=" + num);
num++;
} else {
break;
}
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
AlternatePrintingTest alternatePrintingTest = new AlternatePrintingTest();
new Thread(alternatePrintingTest, "奇数").start();
// 睡眠让奇数线程先行
Thread.sleep(500);
new Thread(alternatePrintingTest, "偶数").start();
}
}
控制台输出:
奇数num=1
偶数num=2
奇数num=3
偶数num=4
。。。。。
偶数num=98
奇数num=99
偶数num=100