2014年5月17日星期六

java.util.concurrent.ExecutorService problem !

ExecutorService executorService = Executors.newCachedThreadPool();
//10个FutureTask
        List<FutureTask> futureTasks = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futureTasks.add(new FutureTask<>(new Callable<String>() {//FutrueTask的构造参数是一个Callable接口或runnable接口
                @Override
                public String call() throws Exception {
                    Thread.currentThread().sleep(1000);
                    return Thread.currentThread().getName();//这里是异步操作
                }
            }));
        }
executorService.invokeAll(futureTasks);

last line prompt : No such constructor. Why ?
------ Solution ---------------------------------------- ----
FutureTask not implement Callable
------ Solution ----------------------------- ---------------

ExecutorService executorService = Executors.newCachedThreadPool ();
/ / 10个FutureTask
List futureTasks = new ArrayList <> ();
for (int i = 0; i <10; i + +) {
futureTasks.add (new FutureTask <> (new Callable () {/ / constructor parameter FutrueTask is a Callable interface or runnable interface
@ Override
public String call () throws Exception {
Thread.currentThread ();
Thread.sleep (1000);
return Thread.currentThread (). getName () ;/ / Here is an asynchronous operation
}
}));
}
for (FutureTask futureTask: futureTasks) {
executorService.execute (futureTask);
}
------ Solution ----------------------------------- ---------

for (FutureTask futureTask : futureTasks) {
    executorService.execute(futureTask);
}

------ Solution ------------------------- -------------------


2 Floor positive solution !
------ For reference only -------------------------------------- -
first look at the Well !

没有评论:

发表评论