摘要:分享牛原创,java callable使用,java Runnable使用。java线程池,java线程返回值。
1.1.1. java callable使用
package com.shareniu.thread; 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 TaskRunable implements Runnable { private String id; public TaskRunable(String id) { this.id = id; } public void run() { System.out.println(id+"-----------"); } public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5); List<Future<String>> list=new ArrayList<Future<String>>(); for (int i = 0; i < 5; i++) { list.add(fixedThreadPool.submit(new TaskRunable(i+""),i+"")); } for (Future<String> future : list) { if (future.isDone()) { String string = future.get(); System.out.println(string); } } fixedThreadPool.shutdown(); } }
输出结果:
0
1
2
3
4
1.1.2. java Runnable使用
package com.shareniu.thread; 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 TaskRunable implements Runnable { private String id; public TaskRunable(String id) { this.id = id; } public void run() { System.out.println(id+"-----------"); } public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5); List<Future<String>> list=new ArrayList<Future<String>>(); for (int i = 0; i < 5; i++) { list.add(fixedThreadPool.submit(new TaskRunable(i+""),i+"")); } for (Future<String> future : list) { if (future.isDone()) { String string = future.get(); System.out.println(string); } } fixedThreadPool.shutdown(); } }
输出:
0-----------
2-----------
3-----------
1-----------
0
4-----------
1
2
3
4
1.1.3. 总结
1.Runnable 方法public void run() 没有返回值并且不能抛异常。
2.Callable接口方法public String call() throws Exception 可以有返回值并且可以抛出异常。
3.返回值得接受是Future对象。
4.线程池跟线程的返回没有什么关系。
分享牛原创(尊重原创 转载对的时候第一行请注明,转载出处来自分享牛http://blog.csdn.net/qq_30739519)