package com.gaiwey.juc;
/**
* 一道面試題:用两个线程交替打印A1B2C3D4E5......
* @author 嚼不烂菠菜
*
*/
public class WaitNotifyTest {
public static void main(String[] args) throws Exception {
final char[] aC = "ABCDEFGHI".toCharArray();
final char[] aI = "123456789".toCharArray();
final Object o = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(o){
for (char c:aC) {
System.out.print(c);
try {
o.notify();
o.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized(o){
for (char c:aI) {
try {
o.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(c);
o.notify();
}
}
}
});
t2.start();
// 线程1保证晚于线程2启动
Thread.sleep(5);
t1.start();
}
}
运行结果:
A1B2C3D4E5F6G7H8I9