一、说明:
经典的线程交互的例子
二、代码:
public class TestThreadAlternate {
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
ThreadAlternateDemo.class.newInstance().exec();
}
}
/**
* 经典的线程交互的例子
*/
class ThreadAlternateDemo {
Object lock = new Object();
char[] arrayInt = "1234567890".toCharArray();
char[] arrayChar = "abcdefghij".toCharArray();
public void exec() {
new Thread(() -> {
synchronized (lock) {
for (char c : arrayInt) {
try {
lock.notify();
lock.wait(); // 让出锁
System.out.print(c);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}, "t1").start();
new Thread(() -> {
synchronized (lock) {
for (char c : arrayChar) {
try {
System.out.print(c);
lock.notify();
lock.wait(); // 让出锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}, "t2").start();
}
}
三、运行结果:
image.png