今天去面試遇見這道題,當(dāng)時(shí)覺得挺簡(jiǎn)單的,結(jié)果寫起來(lái)一緊張卡殼了,回來(lái)想了一下,思路挺明確的,同一個(gè)類,兩個(gè)線程訪問它,一個(gè)打完之后將另一個(gè)喚醒就好了。
代碼如下:
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();
}
}