sleep和interrupt的使用
有兩個線程,driver(司機)和police(警察),其中driver準備睡一個小時後再開始開車,police大喊3句"開車"後,吵醒休眠的線程driver.
public class police_driver_thread {
public static void main(String args[]){
Road road = new Road();
Thread police,driver;
police = new Thread(road);
driver = new Thread(road);
police.setName("警察");
driver.setName("司機");
road.setAttachThread(driver);
driver.start();
police.start();
}
}
class Road implements Runnable{
Thread attachThread;
public void setAttachThread(Thread attachThread) {
this.attachThread = attachThread;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
if(name.equals("司機")){
try {
System.out.println("我是"+name+"在馬路上開車.");
System.out.println("想睡上一個小時後在開車");
Thread.sleep(1000*60*60);
}catch (Exception e){
System.out.println(name+"被警察叫醒了");
}
System.out.println(name+"繼續開車");
}
else if(name.equals("警察")){
for(int i = 1;i<=3;i++){
System.out.println(name+"喊:開車!");
try{
Thread.sleep(50);
}catch (Exception e){
}
}
attachThread.interrupt();//吵醒driver
}
}
}