题目
写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序为12A34B56C......5152Z。要求用线程间的通信。
注:分别给俩个对象构造一个对象O,数字每打印两个或字母每打印一个就执行O.wait().
代码实现
package 第16章多线程.chapter16_09_ThreadLocal;
public class TestThread1 {
public static void main(String[] args) {
Object object = new Object();
new Thread1(object).start();
new Thread2(object).start();
}
}
// 数字打印线程
class Thread1 extends Thread {
private Object obj;
public Thread1(Object obj) {
this.obj = obj;
}
public void run() {
synchronized (obj) {
for (int i = 1; i <= 52; i++) {
System.out.print(i);
if (i % 2 == 0) {
obj.notifyAll();
//打印到能被 2 整除就等待
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
// 字母打印线程
class Thread2 extends Thread {
private Object obj;
public Thread2(Object obj) {
this.obj = obj;
}
public void run() {
synchronized (obj) {
for (int i = 0; i < 26; i++) {
System.out.print((char) ('A' + i));
//打印一个字母就唤醒其他所有线程
obj.notifyAll();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}