今天去面试遇见这道题,当时觉得挺简单的,结果写起来一紧张卡壳了,回来想了一下,思路挺明确的,同一个类,两个线程访问它,一个打完之后将另一个唤醒就好了。
代码如下:
package com.cwj.thread;
/**
* Created by cwj on 18-12-7.
*/
public class Print_letter implements Runnable{
char ch = 97;
@Override
public void run() {
while (true){
synchronized (this){
notify();
try {
Thread.currentThread().sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
if (ch < 123){
System.out.println(Thread.currentThread().getName() + " " + ch);
ch++;
try {
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Print_letter t = new Print_letter();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
t2.start();
}
}