实现代码
public class PrintNumber {
public static void main(String[] args) {
Print print = new Print();
new Thread(print, "线程1").start();
new Thread(print, "线程2").start();
}
}
class Print implements Runnable {
private int num = 1;
@Override
public void run() {
while (true) {
synchronized (this) {
notify();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "打印:" + num);
num++;
if (num >= 100) {
break;
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
演示视频
java两个线程交替打印输出