Callable 和 Future 的试用

简述:

试用一下Callable 和 Future

Callable 和Runnable的区别在于Callable是有返回值的线程


设计:

1)执行一个线程

2)批量执行


1.  线程耗时5秒,得到结果

ExecutorService用来开始线程操作,发现如果使用了Future的get 方法,那么主线程就会停下来等到子线程得到结果之后然后继续执行,

所以计时器的结果 恰恰是Callable线程的开销,为5秒

GetResult.java

package testMultithread;

import java.util.concurrent.Callable;

public class GetResult implements Callable<String> {
	@Override
	public String call() throws Exception {
		Thread.sleep(5000);
		return "Hello World";
	}
}

TestCallableAndFuture.java

package testMultithread;

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


public class TestCallableAndFuture {
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		GetResult getResultThread = new GetResult();
		
		long startTime = System.currentTimeMillis(); 
		Future<String> future = executorService.submit(getResultThread);
		try {
			//5秒之后得到结果
			System.out.println(future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}finally{
			executorService.shutdown();
		}
		long endTime = System.currentTimeMillis(); 
		
		System.out.println("Time Cost: " + (endTime - startTime));
	}

}

输出:



2. 下面是多个Callable执行

GetResult.java

package testMultithread;

import java.util.concurrent.Callable;

public class GetResult implements Callable<String> {
	private static int Num = 0;
	@Override
	public String call() throws Exception {
		Thread.sleep(1000);
		Num++;
		return "The " + Num + "th Hello World";
	}
}

TestCallableAndFuture.java

package testMultithread;

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


public class TestCallableAndFuture {
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(1);
		List<Future<String>> results = new ArrayList<Future<String>>();
		
		long startTime = System.currentTimeMillis(); 
        for(int i = 0; i < 5; i++)
            results.add(executorService.submit(new GetResult()));
		try {
			//每个1秒,总共5秒之后得到结果
			for(Future future : results)
				System.out.println(future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}finally{
			executorService.shutdown();
		}
		long endTime = System.currentTimeMillis(); 
		
		System.out.println("Time Cost: " + (endTime - startTime));
	}

}

输出:



你可能感兴趣的:(Callable 和 Future 的试用)