sow*_*mya 14 java parallel-processing multithreading
每次我都要创建一个可变数量的线程.我这样做是通过创建一个Threads数组并创建多个线程.
但是,我不明白如何启动这些n个线程表现得像多线程概念.我希望他们并行运行.
请指导在这个场所做什么.
Gra*_*ray 37
但是,我不明白如何启动这些n个线程表现得像多线程概念.我希望他们并行运行.
你当然可以使用循环创建一个线程数组:
Thread[] threads = new Thread[NUM_JOBS_TO_CREATE];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
// some code to run in parallel
// this could also be another class that implements Runnable
}
});
threads[i].start();
}
Run Code Online (Sandbox Code Playgroud)
这将导致线程在后台并行运行.然后,您可以稍后与他们一起等待他们全部完成,然后再继续.
// wait for the threads running in the background to finish
for (Thread thread : threads) {
thread.join();
}
Run Code Online (Sandbox Code Playgroud)
但是我不建议自己管理线程,而是建议使用内置的JavaExecutors
.他们为您做的所有这些都更容易管理.此方法的一个好处是它将任务与运行它们的线程分开.例如,您可以启动10个线程来并行运行1000和1000个任务.
这是一些示例ExecutorService
代码:
// create a pool of threads, 10 max jobs will execute in parallel
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// submit jobs to be executing by the pool
for (int i = 0; i < NUM_JOBS_TO_CREATE; i++) {
threadPool.submit(new Runnable() {
public void run() {
// some code to run in parallel
// this could also be another class that implements Runnable
}
});
}
// once you've submitted your last job to the service it should be shut down
threadPool.shutdown();
// wait for the threads to finish if necessary
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅线程执行程序上的Java教程.
基本伪代码:
create x threads, store them in an array or list;
for each thread in the list/array
call start() on the thread object;
Run Code Online (Sandbox Code Playgroud)