题目
代码
package com.thread;
/**
* 字符交替出现
*/
public class CharAlternately {
public static void main(String[] args) {
final Object o = new Object();
String[] aInt = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
char[] aChar = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};
new Thread(()->{
synchronized (o){
for(String c:aInt){
System.out.print(c);
try {
o.notify();//叫醒t2
o.wait();//阻塞自己
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
},"t1").start();
new Thread(()->{
synchronized (o){
for(char c:aChar){
System.out.print(c);
try {
o.notify();//叫醒t1
o.wait();//阻塞自己
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o.notify();
}
},"t2").start();
}
}