Java多线程-实现Callable接口的call()方法,示例

    创建步骤,首先实现Callable接口的call()方法并指定返回值;然后创建实现类实例;FutureTask类使用Callable实现类的实例通过FutureTask的单参数构造器创建FutureTask的实例;通过Thread类的构造器创建Thread类实例,并执行start方法,启动线程;最后通过FutureTask实例的get()方法阻塞拿到Callable实现类的call方法的返回值。

    示例如下,

public class CallableTest implements Callable {
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 5 ; i++) {
            Thread.sleep(Math.round(Math.random()*1000));  //线程随机时长休眠
            System.out.println(Thread.currentThread().getName()+" "+i);
        }
        return Thread.currentThread().getName()+" is completed."; // 返回值
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CallableTest callableTest1 = new CallableTest();
        CallableTest callableTest2 = new CallableTest();
        FutureTask futureTask1 = new FutureTask(callableTest1);
        FutureTask futureTask2 = new FutureTask(callableTest2);
        new Thread(futureTask1,"Thread-1: ").start();
        new Thread(futureTask2,"Thread-2: ").start();
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
    }
}

执行结果,


Thread-2:  0
Thread-2:  1
Thread-1:  0
Thread-2:  2
Thread-1:  1
Thread-2:  3
Thread-2:  4
Thread-1:  2
Thread-1:  3
Thread-1:  4
Thread-1:  is completed.
Thread-2:  is completed.


 

你可能感兴趣的:(多线程,java,thread,多进程)