在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ CompletionSerivce為什么一直阻塞,結(jié)果獲取不到?

CompletionSerivce為什么一直阻塞,結(jié)果獲取不到?

使用的是以下代碼:


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 使用CompletionService解決Future的缺點
 *
 * @author xiaoshu
 */
public class Test1 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        MyCallable username1 = new MyCallable("username1", 5);
        MyCallable username2 = new MyCallable("username2", 4);
        MyCallable username3 = new MyCallable("username3", 3);
        MyCallable username4 = new MyCallable("username4", 2);
        MyCallable username5 = new MyCallable("username5", 1);
        List<Callable> callables = new ArrayList<>();
        callables.add(username1);
        callables.add(username2);
        callables.add(username3);
        callables.add(username4);
        callables.add(username5);

        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        ExecutorCompletionService<Object> csRef = new ExecutorCompletionService<>(poolExecutor);
        for (int i = 0; i < 5; i++) {
            Future future = poolExecutor.submit(callables.get(i));
        }

        for (int i = 0; i < 5; i++) {
            System.out.println("等待打印第" + (i + 1) + "個返回值");
            System.out.println(csRef.take().get());
        }

        //System.out.println("main method End!");
    }
}

class MyCallable implements Callable<String> {
    private String username;
    private long sleepValue;

    public MyCallable(String username, long sleepValue) {
        this.username = username;
        this.sleepValue = sleepValue;
    }

    @Override
    public String call() throws Exception {
        System.out.println(username + " " + sleepValue);
        Thread.sleep(sleepValue);
        return "return " + username;
    }
}

控制臺輸出如下:

clipboard.png

從結(jié)果來看,就像是線程被阻塞了,一直獲取不到結(jié)果,求解!!!

回答
編輯回答
蔚藍色

感謝幫助!
找到原因了.

ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        ExecutorCompletionService<Object> csRef = new ExecutorCompletionService<>(poolExecutor);
        for (int i = 0; i < 5; i++) {
            Future future = csRef.submit(callables.get(i));//這個地方,提交線程使用csRef,而不是之前的線程池
        }
2017年9月9日 23:41
編輯回答
尤禮
@Override
public String call() throws Exception {
    System.out.println(username + " " + sleepValue);
    Thread.sleep(sleepValue);//應(yīng)該是這里時間太短了, csRef.take().get()在等待幾個已經(jīng)完成過的callable了吧。
    return "return " + username;
}
2017年7月30日 15:10