FutureTask这个功能实在是很帅

之前苦于多线程run完之后没有办法返回东西,一直不知道Tiger之后就有这个功能,贴在这里提个醒。


这是主程序

package cn.edu.sysu.execute;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import cn.edu.sysu.thread.GetMessageThread;
import cn.edu.sysu.thread.PrintThread;

public class PrintExecutor {
	
	/**
	 * future task is awesome
	 * */
	public static void main(String[] args) {
		ExecutorService e = Executors.newFixedThreadPool(2);

		Future<String> f1 = e.submit(new GetMessageThread("1", 6));
		Future<String> f2 = e.submit(new GetMessageThread("2", 3));
		Future<String> f3 = e.submit(new GetMessageThread("3", 1));

		try {
			System.out.println(f1.get());
			System.out.println(f2.get());
			System.out.println(f3.get());
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (ExecutionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		e.shutdown();

	}
}
下面这个是Callable的实现

package cn.edu.sysu.thread;

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

public class GetMessageThread implements Callable<String> {

	String msg;
	int wait;
	
	public GetMessageThread(String msg, int wait){
		this.msg=msg;
		this.wait=wait;
		
	}
	
	@Override
	public String call() throws Exception {
		System.out.println(this.msg+" is going to sleep");
		TimeUnit.SECONDS.sleep(wait);
		System.out.println(this.msg+" is going to return");
		
		return "msg:"+msg+" "+new Date(System.currentTimeMillis()).toString();
	}

}

你可能感兴趣的:(java,多线程,callable,executorService)