[JAVA]多线程之实现Callable接口

通过继承Callable方式实现的多线程可以获取线程执行后的返回值

示例代码如下:

public class Counter implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("\tstart");
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        Thread.sleep(4000);
        System.out.println("\tend");
        return sum;
    }
}
public class MutiThreadTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Counter counter = new Counter();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(counter);
        new Thread(integerFutureTask).start();

        // 该方法会阻塞调用线程
        Integer integer = integerFutureTask.get();
        System.out.println(integer);
    }
}

 

上一篇:调用日志输出错误:TypeError: 'int' object is not callable


下一篇:在php中使用callable