1. 程式人生 > >Java非同步執行任務常用方式FutureTask和ExecutorService

Java非同步執行任務常用方式FutureTask和ExecutorService

1,ExecutorService結合線程池

package com.asyn;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceTest {

	private static ExecutorService executor = Executors.newFixedThreadPool(1);

	public static void main(String[] args) {
		asynTask();
		synTask();
		System.out.println(new Date() + " 主執行緒執行結束");
	}

	/**
	 * 非同步執行的方法
	 */
	public static void asynTask() {
		executor.execute(new Runnable() {
			public void run() {
				try {
					// 模擬非同步方法執行的過程,耗時10秒
					Thread.sleep(10000);
					System.out.println(new Date() + " 非同步方法執行結束");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		executor.shutdown();
	}

	/**
	 * 同步執行的方法
	 */
	public static void synTask() {
		System.out.println(new Date() + " 同步方法執行結束");
	}

}
執行結果:

2,FutureTask

package com.asyn;

import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class FutureTaskTest {

	public static void main(String[] args) {
		asynTask();
		synTask();
		System.out.println(new Date() + " 主執行緒執行完畢");
	}

	public static void asynTask() {
		FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
			public Integer call() throws Exception {
				Thread.sleep(10000);
				System.out.println(new Date() + " 非同步方法執行完畢");
				return 1;
			}
		});
		Thread thread = new Thread(task);
		thread.start();
	}
	
	public static void synTask() {
		System.out.println(new Date() + " 同步方法執行完畢");
	}

}
執行結果: