【java线程】Callable实现类的两种运行方式


实现类:

package com.hy.lab.future;

import java.util.Random;
import java.util.concurrent.Callable;

public class Counter implements Callable {
    @Override
    public Integer call() throws Exception {
        Random rnd=new Random();
        int result=rnd.nextInt(10);
        Thread.sleep(1000*result);

        return result;
    }
}

两种运行方式:

package com.hy.lab.future;

import java.util.concurrent.*;

public class Test {
    public static void main(String[] args) throws Exception{
        test1();
    }

    // 使用FutureTask执行Counter
    private static void test1() throws Exception{
        FutureTask ft=new FutureTask(new Counter());
        new Thread(ft).start();
        int result=ft.get();// 阻塞
        System.out.println(result);
    }

    // 使用线程池执行Counter
    private static void test2() throws Exception{
        ExecutorService es=Executors.newCachedThreadPool();
        Future ft=es.submit(new Counter());
        int result=ft.get();// 阻塞
        System.out.println(result);

        es.shutdown();
    }
}

END

相关