java并发--Callable的使用

在java并发中提供了Callable<T>的一个接口,可以在线程中返回一个参数,这是接口Runable所做不到的。。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.ArrayList;
import java.util.Iterator;
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;
 
public class CallableTest {
    /**
     * 可以返回一个参数
     * @author Administrator
     *
     */
    class TaskCallable implements Callable<String> {
        int id;
 
        TaskCallable(int id) {
            this.id = id;
        }
        /**
         * 线程中可以返回一个参数
         */
        @Override
        public String call() throws Exception {
            return "xxxx" + id;
        }
 
    }
 
    public static void main(String[] args) {
        CallableTest test = new CallableTest();
        ArrayList<Future<String>> arrFuture = new ArrayList<Future<String>>();//利用future储存
        ExecutorService executorServer = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < 10; i++) {
                Future<String> future = executorServer
                        .submit(test.new TaskCallable(i));//submit产生futrue对象
                arrFuture.add(future);
 
            }
            for (Future<String> future : arrFuture) {
                System.out.println(future.get());
            }
        } catch (InterruptedException e) {
            System.out.print(e);
        } catch (ExecutionException e) {
            System.out.print(e);
        } finally {
            executorServer.shutdown();
        }
 
    }
}

 call函数返回一个参数,跟Runable所不同的是Runable是调用excute(Thread),Callable是调用

1
submit(Thread).

java并发--Callable的使用,布布扣,bubuko.com

java并发--Callable的使用

上一篇:javascript的回调函数


下一篇:java服务器搭建(一)日志系统