Quantcast
Channel: IT社区推荐资讯 - ITIndex.net
Viewing all articles
Browse latest Browse all 15845

java 线程池使用 Runnable&Callable&Future

$
0
0

1. 创建线程池

ExecutorService executorService = Executors.newCachedThreadPool();

 

2. 执行一次线程,调用Runnable接口实现

Future<?> future = executorService.submit(new DefaultRunnable());
System.out.println(future.get());

 当线程池执行Runnable后,返回的Future.get()总是null

 

DefaultRunnable代码如下:

package threadpool;

public class DefaultRunnable implements Runnable {
	private int count = 1;
	
	@Override
	public void run() {
		System.out.println("the count in default runnable is ["+count+++"]");
	}

}

 

3. 执行一次线程,调用Callable接口实现

Future<?> future = executorService.submit(new DefaultCallable());
System.out.println(future.get());

 当线程池执行Callable时,返回的Future.get() 会返回Callable的返回值

 

DefaultCallable代码如下:

package threadpool;

import java.util.concurrent.Callable;

public class DefaultCallable implements Callable<Object> {
	private int count =1;
	@Override
	public Object call() throws Exception {
		return count++;
	}

}

 

4. 关闭线程池

executorService.shutdown();

 



已有 0人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐




Viewing all articles
Browse latest Browse all 15845

Trending Articles