Executor接口实现线程有返回值和无返回值两种方式

Executor是JDK5引入的接口,在并发包里,提供了耦合度更低,线程组管理的多线程实现方式,其中ExecutorService接口继承自Executor接口,分别提供了有返回值和无返回值的线程调用:

public class Example1 {

    public static void main(String args[]) {
        // For runnable call, traditional thread implementation
        Thread runner = new Thread(new Runner());
        runner.start();


	//Call Executor method execute(), without return value
        Executor ex = Executors.newFixedThreadPool(2);
        ex.execute(new Runner());

        //ExecutorService extends Executor , call ExecutorService method submit() with return value getting from Future interface.
         ExecutorService es = Executors.newFixedThreadPool(3);
         Future<Integer> f = es.submit(new CallableRunner());
         int rtv = 0;
         try {
         rtv = f.get();
         } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         } catch (ExecutionException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
         finally {
         es.shutdown();
         }
         if (rtv == 7) {
         System.out.println("Callable call is finished.");
         }
    }
}

class Runner implements Runnable {

    public void run() {
        System.out.println("Runner is running.");
    }


}

class CallableRunner implements Callable<Integer> {

    public Integer call() {
        System.out.println("CallableRunner starts to run.");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 7;
    }
}

如若转载,请说明出处! http://blog.csdn.net/xukunddp


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值