多线程 Callable方式创建多线程

public class JavaDemo {
    public static void main(String[] args) throws ParseException {

        CallableDemo cd = new CallableDemo();
        FutureTask<Long> task = new FutureTask<>(cd);
        new Thread(task).start();

        try {
            
            //get方法未执行前,后面的代码都得等着,与闭锁的功能相同
            Long sum = task.get();
            
            System.out.println("---------------------");
            System.out.println(sum);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }
}

class CallableDemo implements Callable<Long> {


    @Override
    public Long call() throws Exception {

        long sum = 0;
        for (int i = 1; i <= Integer.MAX_VALUE; i++) {
            sum += i;
        }
        return sum;
    }
}

 

posted @ 2020-04-30 16:32  地中有山  阅读(265)  评论(0编辑  收藏  举报