JUC併發編程學習筆記-08-Callable

視頻鏈接
在這裏插入圖片描述
在這裏插入圖片描述
可以有返回值,可以拋出異常

package callable;

import org.omg.PortableServer.THREAD_POLICY_ID;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //new Thread(new MyThread()).start();不要用這種
        //new Thread(new FutureTask<V>()).start();
        //new Thread(new FutureTask<V>(callable)).start();
        MyThread thread = new MyThread();
        //適配類
        FutureTask futureTask = new FutureTask(thread);
        new Thread(futureTask,"A").start();
        new Thread(futureTask,"B").start();//結果會被緩存,效率高!!!!!!!!!!!!!!
        Integer o = (Integer)futureTask.get();//獲取callable的返回結果,這個get方法可能會產生阻塞!!!!!!!!
        System.out.println(o);
    }
}
class MyThread implements Callable<Integer> {

    @Override
    public Integer call() {
        System.out.println("132313"+Thread.currentThread().getName());//隨機的
        return 12;
    }


}

結果會被緩存,可能會阻塞

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章