1. 程式人生 > >方法被阻塞,一直要等到線程任務返回結果的例子

方法被阻塞,一直要等到線程任務返回結果的例子

會有 sys current 返回結果 dex shutdown imp bmi getname

package cn.itcast_01_mythread.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* callable 跟runnable的區別:
* runnable的run方法不會有任何返回結果,所以主線程無法獲得任務線程的返回值
*
* callable的call方法可以返回結果,但是主線程在獲取時是被阻塞,需要等待任務線程返回才能拿到結果
* @author
*
*/
public class ThreadPoolWithcallable {

public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(4);

for(int i = 0; i < 10; i++){
Future<String> submit = pool.submit(new Callable<String>(){
@Override
public String call() throws Exception {
//System.out.println("a");
Thread.sleep(5000);
System.out.println("b--"+Thread.currentThread().getName() +" 我在線程裏面執行");
return "b--"+Thread.currentThread().getName();
}
});
//從Future中get結果,這個方法是會被阻塞的,一直要等到線程任務返回結果
System.out.println("我不是阻塞的,啦啦啦啦");
System.out.println(submit.get());
}
pool.shutdown();

}

}


反之,不阻塞,就是會繼續執行不會因為子線程還沒有結束而等待,而被阻塞的方法,這會因為某個子線程還沒有結束而等待

方法被阻塞,一直要等到線程任務返回結果的例子