/**
* @author 主线程
*
*/
public class MainThread extends Thread{
protected long timeOut; //超时时间
protected boolean isOverTime = false; //超时状态为否
public MainThread(long timeOut){
this.timeOut = timeOut;
}
public synchronized void checkTime(){//修改超时状态,改为超时
isOverTime = true;
}
public void run(){
try{
sleep(10 * 1000);//还有10秒才能乘车
if(isOverTime) {//判断汽车是否已经启动
System.out.println("主线程:超时,汽车已经走了");
}else {
System.out.println("主线程:乘车");
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
/**
* @author 守护线程
*
*/
class ProtestThread extends Thread {
MainThread MainThread;
public ProtestThread(MainThread thread) {
this.MainThread = thread;
this.setDaemon(true); // 设置成为守护线程
}
@Override
public void run() {
try {
sleep(MainThread.timeOut * 1000);// 离汽车启动还有timeOut秒
MainThread.checkTime(); // 时间到,设置超时状态
System.out.println("保护线程:汽车启动,出发");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MainThread thread = new MainThread(5);//设置超时时间为5秒
thread.start();//开启主线程
ProtestThread protestThread = new ProtestThread(thread);
protestThread.start();//开启守护线程
}
保护线程:汽车启动,出发
主线程:超时,汽车已经走了