shs*_*mer 50 java concurrency multithreading
我正在寻找实现以下内容的最简单,最直接的方法:
n同时运行任务.n到达,没有更多的工人开始,直到运行的线程数降回到低于n.eri*_*son 56
我认为Executors.newFixedThreadPool符合您的要求.有许多不同的方法可以使用生成的ExecutorService,具体取决于您是希望返回主线程的结果,还是任务是完全自包含的,以及您是否有预先执行的任务集合,或者任务是否排队以响应某些事件.
Collection<YourTask> tasks = new ArrayList<YourTask>();
YourTask yt1 = new YourTask();
...
tasks.add(yt1);
...
ExecutorService exec = Executors.newFixedThreadPool(5);
List<Future<YourResultType>> results = exec.invokeAll(tasks);
Run Code Online (Sandbox Code Playgroud)
或者,如果要执行新的异步任务以响应某些事件,您可能只想使用ExecutorService的简单execute(Runnable)方法.
Fab*_*eeg 25
/* Get an executor service that will run a maximum of 5 threads at a time: */
ExecutorService exec = Executors.newFixedThreadPool(5);
/* For all the 100 tasks to be done altogether... */
for (int i = 0; i < 100; i++) {
/* ...execute the task to run concurrently as a runnable: */
exec.execute(new Runnable() {
public void run() {
/* do the work to be done in its own thread */
System.out.println("Running in: " + Thread.currentThread());
}
});
}
/* Tell the executor that after these 100 steps above, we will be done: */
exec.shutdown();
try {
/* The tasks are now running concurrently. We wait until all work is done,
* with a timeout of 50 seconds: */
boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
/* If the execution timed out, false is returned: */
System.out.println("All done: " + b);
} catch (InterruptedException e) { e.printStackTrace(); }
Run Code Online (Sandbox Code Playgroud)
Executors.newFixedThreadPool(INT)
Executor executor = Executors.newFixedThreadPool(n);
Runnable runnable = new Runnable() {
public void run() {
// do your thing here
}
}
executor.execute(runnable);
Run Code Online (Sandbox Code Playgroud)