Callable interface of Thread

Callable interface description

Insert picture description here

Simple example

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
 * @author layman
 * @date 2021/2/10
 */
public class Demo01 {
    
    
    public static void main(String[] args) throws ExecutionException, InterruptedException {
    
    
        Callable<Integer> callable = new Demo01Callable();
        FutureTask<Integer> task = new FutureTask(callable);
        Thread t = new Thread(task);
        t.setName("测试callable线程");
        t.start();
        System.out.println("线程返回的值为: " + task.get());
    }
}
class Demo01Callable implements Callable<Integer>{
    
    

    @Override
    public Integer call() throws Exception{
    
    
        System.out.println(Thread.currentThread().getName()+"调用了call方法");
        int val = (int)(Math.random()*10);
        System.out.println("准备返回的值是: " + val);
        return val;
    }
}

Guess you like

Origin blog.csdn.net/single_0910/article/details/113780707