线程池与Callable更配哦

来源:互联网 发布:新闻表数据库设计 编辑:程序博客网 时间:2024/05/20 23:02

概述

Callable介绍见:http://blog.csdn.net/zengmingen/article/details/53288119

多线程介绍见:http://blog.csdn.net/zengmingen/article/details/53284999


代码

TaskCallable.java

package multithreading.pool;import java.util.concurrent.Callable;public class TaskCallable implements Callable<String>{/**线程编号*/private int tNo;public TaskCallable(int tNo){this.tNo=tNo;}@Overridepublic String call() throws Exception {String tName=Thread.currentThread().getName();long currentTimeMillis = System.currentTimeMillis();System.out.println(tNo+"-"+tName+" start time is:"+currentTimeMillis/1000);try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(tNo+"-"+tName+ " is working...");return "the thread is "+tNo;}}

TestPool.java

package multithreading.pool;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 TestPool {public static void main(String[] args) throws Exception, ExecutionException {List<Future<String>> futures = new ArrayList<Future<String>>();ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2);for (int i = 0; i < 5; i++) {Future<String> future = newFixedThreadPool.submit(new TaskCallable(i));futures.add(future);}// 打印结果for (Future<String> f : futures) {boolean done = f.isDone(); // 从结果的打印顺序可以看到,即使未完成,也会阻塞等待System.out.println(done ? "已完成" : "未完成");//从Future中get结果,这个方法是会被阻塞的,一直要等到线程任务返回结果System.out.println("已完成线程返回future结果: " + f.get());}newFixedThreadPool.shutdown();}}

运行结果

0-pool-1-thread-1 start time is:1479808023
未完成
1-pool-1-thread-2 start time is:1479808023
0-pool-1-thread-1 is working...
1-pool-1-thread-2 is working...
已完成线程返回future结果: the thread is 0
已完成
已完成线程返回future结果: the thread is 1
未完成
2-pool-1-thread-1 start time is:1479808024
3-pool-1-thread-2 start time is:1479808024
3-pool-1-thread-2 is working...
2-pool-1-thread-1 is working...
4-pool-1-thread-2 start time is:1479808026
已完成线程返回future结果: the thread is 2
已完成
已完成线程返回future结果: the thread is 3
未完成
4-pool-1-thread-2 is working...
已完成线程返回future结果: the thread is 4




0 0
原创粉丝点击