//设计两个线程,其中一个线程打印数字1、2、3、……26,另外一个线程打印A、B、C、……Z。每个线程打印两次,交替进行。
// 例如:1,2,A,B,3,4,C,D,……
public class s8_2 {
static class PrintRunnable implements Runnable {
//定义一个锁
private Object lock;
public PrintRunnable(Object lock) {
this.lock = lock;
}
@Override
public void run() {
synchronized (lock) {
for (int i = 1; i < 26; i=i+2) {
if (Thread.currentThread().getName() == "打印数字") {
//打印数字1-26
System.out.println((i ));
System.out.println((i+1));
// 唤醒其他在等待的线程
lock.notifyAll();
try {
// 让当前线程释放锁资源,进入wait状态
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else if (Thread.currentThread().getName() == "打印字母") {
// 打印字母A-Z
System.out.println((char) ('A'+i-1 ));
System.out.println((char) ('A'+i));
// 唤醒其他在等待的线程
lock.notifyAll();
try {
// 让当前线程释放锁资源,进入wait状态
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//测试main方法
public static void main(String[] args) {
Object lock = new Object();
new Thread(new PrintRunnable(lock), "打印数字").start();
new Thread(new PrintRunnable(lock), "打印字母").start();
}
}