優雅的結束線程

  1. 使用interrupt()打斷
    代碼:
    public class CloseThread1 {
    	public static void main(String[] args) {
        	Thread thread = new Thread(() -> {
            	try {
                	Thread.sleep(10_1000);//模擬執行的任務
            	} catch (InterruptedException e) {
                	System.out.println("任務強制結束!");
            	}
        	});
        	thread.start(); //啓動線程,執行任務
        	try {
            	Thread.sleep(1000);//主線程等待任務執行1s
            	thread.interrupt();//打斷任務執行
        	} catch (InterruptedException e) {
            	e.printStackTrace();
        	}
    	}
    }
    
  2. 使用Thread.interrupted()優化異常處理:
    代碼:
    public class CloseThread2 {
    	public static void main(String[] args) {
        	Thread thread = new Thread(() -> {
            	while (true) {  //模擬任務
                	if (Thread.interrupted()) {
                    	System.out.println("任務強制結束!");
                    	break;
                	}
            	}
        	});
        	thread.start(); //啓動線程,執行任務
        	try {
            	Thread.sleep(1000);//主線程等待任務執行1s
            	thread.interrupt();//打斷任務執行
        	} catch (InterruptedException e) {
            	e.printStackTrace();
        	}
    	}
    }
    
  3. 使用daemon+join()+interrupt()製作限時結束
    代碼:
    public class CloseThread3 {
    	//爲了放在一起才使用的內部類
    	class ThreadService{
       		private Thread executor;	//執行器
        	private boolean isFinish = false;	//任務執行結束標誌
    
        	public void execute(Runnable task) {
            	executor = new Thread(() -> {
                	Thread runner = new Thread(task);
                	runner.setDaemon(true);	//設置爲守護線程
                	runner.start();
                	try {
                    	runner.join();	//等待任務執行完畢
                    	isFinish = true;
                	} catch (InterruptedException e) {
                    	System.out.println("任務強制結束!");
                	}
            	});
            	executor.start();
        	}
    
        	public Long shutdown(Long time) {
            	long concurrentTime = System.currentTimeMillis();
            	while (!isFinish) {
                	if (System.currentTimeMillis()-concurrentTime >= time) {
                    	System.out.println("任務超時!");
                    	executor.interrupt();
                    	break;
                	}
                	try {
                    	Thread.sleep(1);
                	} catch (InterruptedException e) {
                    	System.out.println("執行線程被打斷!");
                	}
            	}
            	return System.currentTimeMillis() - concurrentTime;
        	}
    	}
    
    	public static void main(String[] args) {
        	ThreadService service = new CloseThread3().new ThreadService();
        	service.execute(() ->{while (true){}}); //模擬任務執行
        	System.out.println("任務執行時間:" + service.shutdown(1000L));
    	}
    }
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章