您的当前位置:首页正文

带返回值的线程Callable

2024-11-30 来源:个人技术集锦

Runnable与Callable

接口定义
Callable接口

public interface Callable<V>{
    V call() throws Exception;
}

Runnable接口

public interface Runnable {
    public abstract void run();
}

Callable使用步骤

1.编写类实现Callable接口,实现call方法

class XXX implements Callable<T> {
    @Override
    public <T> call() throws Exception {
        return T;
    }
}

2.创建FutureTask对象,并传入第一步编写的Callable类对象

FutureTask<Integer> future = new FutureTask<>(callable);

3.通过Thread,启动线程

new Thread(future).start();

Runnable与Callable的相同点

1.都是接口
2.都可以编写多线程程序
3.都采用Thread.start()启动线程

Runnable与Callable的不同点

1.Runnable没有返回值,而Callable可以返回执行结果
2.Callable接口的call()允许抛出异常,Runnable的run()不能抛出

Callable获取返回值

Callablee接口支持返回执行结果,需要调用FutureTask.get()得到,此方法会阻塞主进程的继续往下执行,如果不调用不会阻塞。

话不多说上才艺

public class Demo2 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable<Integer> c = new MyCallable();
        FutureTask<Integer> task = new FutureTask<>(c);
        new Thread(task).start();
        for (int i =0;i<10;i++){
            System.out.println(i);
            Thread.sleep(100);
        }
    }

    static class MyCallable implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            //Thread.sleep(3000);
            for (int i =0;i<10;i++){
                System.out.println(i);
                Thread.sleep(100);
            }
            return 100;
        }
    }
}

此时的运行结果:

public class Demo2 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        Callable<Integer> c = new MyCallable();
        FutureTask<Integer> task = new FutureTask<>(c);
        new Thread(task).start();
        Integer j =task.get();
        System.out.println("收到返回值为"+j);
        for (int i =0;i<10;i++){
            System.out.println(i);
            Thread.sleep(100);
        }
    }

    static class MyCallable implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            //Thread.sleep(3000);
            for (int i =0;i<10;i++){
                System.out.println(i);
                Thread.sleep(100);
            }
            return 100;
        }
    }
}

显示全文