欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

线程的第三种创建方式-Callable的使用

程序员文章站 2022-03-10 17:15:44
线程的第三种创建方式Callable的使用public class MyThread implements Callable { @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName()+ ":11111111"); return 1024; }}public class CallableDemo...

线程的第三种创建方式

Callable的使用

public class MyThread implements Callable {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+ ":11111111");
        return 1024;
    }
}
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask<>(new MyThread());

        Thread thread = new Thread(futureTask,"AAA");
        thread.start();

        System.out.println(futureTask.get());
    }
}
AAA:11111111
1024

futureTask.get()建议放在代码的最后面,否则main线程会等待子线程执行完才会执行。

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());

        Thread thread = new Thread(futureTask,"AAA");
        thread.start();

        System.out.println(Thread.currentThread().getName()+"*********");
        int a = 1000;
        while (!futureTask.isDone()){
            System.out.println("未完成");
        }
        System.out.println("------------------------完成");
        int number = futureTask.get();

        System.out.println(a+number);
    }
}

可以加个 while (!futureTask.isDone()){}应用

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());

        new Thread(futureTask,"AAA").start();
        new Thread(futureTask,"BBB").start();

        System.out.println(Thread.currentThread().getName()+"*********");
        int a = 1000;
        int number = futureTask.get();
        System.out.println(a+number);
    }
}
结果:
main*********
AAA:11111111
2024

总结:
两个线程调用同一个任务,只会打印一次,AAA线程或者BBB线程进入。 
除非申请两个不通的任务,就是调用两次
FutureTask<Integer> futureTask2 = new FutureTask<>(new MyThread());
new Thread(futureTask2,"BBB").start();


本文地址:https://blog.csdn.net/qq_41583016/article/details/111991130

相关标签: java 线程池