Java多线程,两个线程交替打印(jdk 1.8)
public class AlternatePrint {
public static int i = 0;
public static Object lock = new Object();
public static void main(String[] args) {
new Thread(() -> {
while (true) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " i = " + i++);
lock.notify();
try {
lock.wait();
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
}
}).start();
new Thread(() -> {
while (true) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + " i = " + i++);
lock.notify();
try {
lock.wait();
Thread.sleep(1000);
}
catch (InterruptedException e) {
}
}
}
}).start();
}
}
打印结果