java--守护线程处理超时任务

版权声明:本文为博主原创文章,如需转载请标明出处。 https://blog.csdn.net/DGH2430284817/article/details/87274616

任务背景:

          一个人要坐汽车,汽车还有5秒就启动了,但是那个人还有10秒才能到达车上,一个主线程去做乘车的任务,一个守护线程做汽车启动的任务。

主线程:

/**
 * @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();//开启守护线程
	}

结果:

保护线程:汽车启动,出发
主线程:超时,汽车已经走了

猜你喜欢

转载自blog.csdn.net/DGH2430284817/article/details/87274616