Sam*_*ami 1 java parallel-processing multithreading
我有一个方法,它采取一个列表并对其进行一些处理,它更新另一个全局列表.我需要运行此方法的多个实例,并行输入不同的列表.多线程支持这个吗?如果是,我怎么能使用它,即:我应该在线程中放什么?例子受到高度赞赏.
我想在线程类中有一个静态列表,它在运行时由线程的不同实例更新(列表包含字符串和计数器,因此更新是添加新字符串或增加现有字符串的计数器).. i需要读取每10秒钟添加到此全局列表中的内容并打印它...正在使用适合此的静态列表以及如何使其线程安全?
是的,这是多线程编程的一种常见用法.
class ListProcessor implements Runnable {
/* field/s representing param/s */
public ListProcessor(/* param/s */) {
/* ... */
}
@Override
public void run() {
/* process list */
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当你想要实际处理一些列表时.
class SomeClass {
ExecutorService listProcessor;
public SomeClass(/* ... */) {
listProcessor = ExecutorService.newFixedThreadPool(numThreads);
/* for each thread, however you want to do it */
listProcessor.execute(new ListProcessor(/* param/s */));
/* when finished adding threads */
listProcessor.shutdown();
/* note that the above two lines of code (execute/shutdown) can be
* placed anywhere in the code. I just put them in the constructor to
* facilitate this example.
*/
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3438 次 |
| 最近记录: |