情景:有一个实现了Callable<String>的任务类Taske,在MainClass中定义了一个ArrayList<Taske> tList;MainClass中有一个固定大小的线程池ExecutorService pool,大小为5。有方法一直往tList中添加元素。
问题:希望能实现 让线程池中的线程都工作,如果一个线程完成了当前工作,又去取另一个任务,知道说有任务完成,关闭线程池。一个线程在执行一个任务时,希望任务的返回值中包含该线程的线程号!
问题:希望能实现 让线程池中的线程都工作,如果一个线程完成了当前工作,又去取另一个任务,知道说有任务完成,关闭线程池。一个线程在执行一个任务时,希望任务的返回值中包含该线程的线程号!
问题:希望能实现 让线程池中的线程都工作,如果一个线程完成了当前工作,又去取另一个任务,知道说有任务完成,关闭线程池。一个线程在执行一个任务时,希望任务的返回值中包含该线程的线程号!线程池什么时候关闭掉?红色和绿色部分很矛盾!
ExecutorService pool = Executors.newFixedThreadPool(5);
List<Task> tasks = new ArrayList<Task>(1000);
for (int i = 0; i < 1000; i++) {
tasks.add(new Task(i));
}
List<Future<String>> futureList = pool.invokeAll(tasks);
for (Future<String> future : futureList) {
System.out.println(future.get());
}
pool.shutdown();
} static class Task implements Callable<String> { private final int taskId; public Task(int taskId) {
this.taskId = taskId;
} public String call() throws Exception {
return taskId + " in " + Thread.currentThread().getName();
}
}
import java.util.concurrent.Executors;
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2);//两个线程
int i = 1000;
while(i-- > 0) {
newFixedThreadPool.execute(new Runnable() {
public void run() {
System.out.println("线程ID:" + Thread.currentThread().getId());
try {
Thread.sleep(500);
} catch (Exception e) {}
}
});
}
System.out.println("下面调用shutdown,如果还在打印’线程ID:xx‘表示线程还没执行完,shutdown调用后在等待");
newFixedThreadPool.shutdown();
}
}
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
pool-1-thread-2
....后面的都是线程2怎么线程2用得那么多次,其他两线程没怎么被用到?