Java 线程池的使用实例(包括Runnable和Callable)

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

/**
 * 通过Executor接口的四个工厂方法来实现四种线程池。
 * 每一个线程都是通过调用execute(Runnable command) 方法来执行,该方法接收一个Runnable 实例。
 * @author ZYK
 *
 */
public class CacheThread  {	
	
	public static void main(String args[]){
	
		/*
		 * Executors 提供了一一系列工厂方法来创建线程池,返回的线程池都实现了ExecutorServie接口
		 * 1. Executors.newCachedThreadPool();   //可缓存的线程池
		 * 2. Executors.newScheduledThreadPool(int ); //支持定时和周期性的任务的线程池
		 * 3. Executors.newFixedThreadPool(int nThreads); // 固定数目的线程池
		 * 4. Executors.newSingleThreadExecutor();  //但线程话的线程池
		 */		
		ExecutorService cacheThread =  Executors.newCachedThreadPool();
		//ExecutorService cacheThread =  Executors.newSingleThreadExecutor();
		//ExecutorService cacheThread =  Executors.newScheduledThreadPool(4);
		//ExecutorService cacheThread =  Executors.newFixedThreadPool(4);

		
		
		for(int i=0; i<20; i++){
			final int index = i;
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(i);
			cacheThread.execute(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getState());
					System.out.println(Thread.currentThread().getName() + "线程被调用了");
					System.out.println(Thread.currentThread().getState());
				}
			});
		}
//		System.out.println(cacheThread.isShutdown());
		//关闭方法,调用后执行之前提交的任务,不再接受新的任务
//		cacheThread.shutdown();
//		System.out.println(cacheThread.isShutdown());
		//是否终止
//		System.out.println(cacheThread.isTerminated());
		//从语义上可以看出是立即停止的意思,将暂停所有等待处理的任务并返回这些任务的列表
//		cacheThread.shutdownNow();
		
	}

}

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

/**
 * 通过线程池来执行任务,和Runnable不同的是,这种方法实现了Callable接口。
 * 可以被ExecutorService执行,但是Runnable任务没有返回值,而Callable任务有返回值
 * @author ZYK *
 */
public class CallableTask {
	
	public static void main(String args[]){
		//这里通过newCacheThread()方法来实现线程池,当然也可以用其他三种方法
		ExecutorService executorService = Executors.newCachedThreadPool();
		//Future 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。
		//计算完成后只能使用 get 方法来获取结果,如有必要,计算完成前可以阻塞此方法。
		ArrayList<Future<String>> resultList = new ArrayList<Future<String>>();
		
		//创建10个任务并执行
		for(int i=0; i < 10; i++){
			//使用ExecutorService执行Callalbe类型的任务,并将结果保存在future变量中
			Future<String> future = executorService.submit(new TaskWithResult(i));
			//将任务执行结果存储在List中。
			resultList.add(future);
		}
		for (Future<String> fs : resultList){
			
			try {
				 //一直等待Future的返回结果,直到返回完成,打印输出返回结果。
				while (!fs.isDone());
				System.out.println(fs.get());
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				//启动一次顺序关闭,执行以前提交的任务,但不接受新任务
				executorService.shutdown();
			}
			}
			
		}
	}


/**
 * @author ZYK
 *实现了Callable 接口,重新定义了call()方法。
 *在此类中,我们可以自定义任务Callable的具体实现和功能,来达到既定的目的。
 *通过调用call()函数,可以得到要返回的结果
 */
class TaskWithResult implements Callable<String>{
	private int id;
	
	/**
	 * 构造函数
	 * @param id 线程执行时的参数
	 */
	public TaskWithResult(int id){
		this.id = id;
	}
	public String call(){
		System.out.println(Thread.currentThread().getName() + "线程被调用了");
		//返回提示信息,该返回结果将在Future的get方法中得到。
		String res = "call() 方法被调用,任务返回的结果是:" + id + "  " + Thread.currentThread().getName() ;
		return res;
	}
}


转载于:https://my.oschina.net/mzzyk/blog/398730

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值