模擬取消線程池中任務

package com.helloword;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
	private volatile boolean cancelFlag = false;
	private final ExecutorService threadPool = Executors.newFixedThreadPool(1);

	public static void main(String[] args) {
		Test p = new Test();
		p.threadPool.execute(new Runnable() {

			@Override
			public void run() {
				while (true) {
					if (p.cancelFlag) {
						System.out.println(Thread.currentThread());
						System.out.println("線程池任務已取消,即將退出");
						Thread.currentThread().interrupt();
						break;
					}
					System.out.println("線程池任務在進行");
				}
			}
		});

		Timer t = new Timer();
		t.schedule(new TimerTask() {
			@Override
			public void run() {
				System.out.println("定時任務開始執行,即將準備取消線程池任務");
				System.out.println(Thread.currentThread());
				p.cancelFlag = true;
				try {
					System.out.println("定時任務阻塞");
					Thread.sleep(3000);
					System.out.println("定時任務阻塞結束");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					System.out.println("定時任務退出");
				}
			}
		}, 1000);

		// A Java application continues to execute (the virtual machine continues to
		// live)
		// as long as any non-daemon threads are still running.When all non-daemon
		// threads
		// of a Java application terminate,the virtual maching
		// instance will exit.
		try {
			Thread.sleep(4500);
			System.out.println(Thread.currentThread());
			System.out.println("一段時間後,關閉線程池和定時器線程 。退出程序");
		} catch (

		InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally {
			p.threadPool.shutdownNow();
			t.cancel();
		}

	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章