java中多线程的并行执行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19770721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parallel Execution of multiple threads in java
提问by user907810
I have to execute multiple instances of my class concurrently. i have written the following code below. I have done it in two ways. But I don't see the difference. What is the right way to have parallel running threads?
我必须同时执行我的类的多个实例。我在下面编写了以下代码。我已经通过两种方式做到了。但我看不出有什么区别。并行运行线程的正确方法是什么?
Thanks.
谢谢。
Here the snippet:
这里的片段:
public class MyClass {
public MyClass() {
runnable = true;
}
public boolean isRunnable() {
return runnable;
}
public static void main(String[] args) throws InterruptedException {
/* METHOD 1
MyClass myclass = new MyClass();
if (myclass.isRunnable()) {
for (int i = 0; i < loop; i++) {
myclass.execTask();
Thread.sleep(sleep);
}
}
*/
//METHOD 2
final MyClass myclass = new MyClass();
ExecutorService threadPool = Executors.newFixedThreadPool(threadNo);
for (int i = 0; i < threadNo; i++) {
threadPool.submit(new Runnable() {
public void run() {
for (int i = 0; i < loop; i++) {
myclass.execTask();
try {
Thread.sleep(sleep);
} catch (InterruptedException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
}
threadPool.shutdown();
public void execTask(){
.........
}
}
}
回答by Charles Forsythe
The difference between your two methods is that in "Method 2," you may actually have multiple threads of execution (assuming that threadNo
is greater than 1). Method 2 allows for multiple work threads to grab a Runnable
and call execTask
(by calling run
) in parallel (concurrently, to be precise). The pause in "Method 2" does pretty much nothing.
您的两种方法之间的区别在于,在“方法 2”中,您实际上可能有多个执行线程(假设threadNo
大于 1)。方法 2 允许多个工作线程并行(准确地说是并发)获取 aRunnable
并调用execTask
(通过调用run
)。“方法 2”中的停顿几乎没有任何作用。
"Method 1" executes entirely on the "Main" thread. It calls execTask
, waits, and then calls it again. This will call the execution some number of times serially.
“方法 1”完全在“主”线程上执行。它调用execTask
,等待,然后再次调用它。这将连续多次调用执行。
(I assume this is pseudo-code because parts of it won't compile.)
(我认为这是伪代码,因为它的一部分无法编译。)
Here is a cleaned-up "Method 2". Note that I have threadNo
worker threads (it helps if this is larger than 1) and I create loop
Runnables
.
这是一个清理过的“方法2”。请注意,我有threadNo
工作线程(如果它大于 1,它会有所帮助)并且我创建了loop
Runnables
.
ExecutorService threadPool = Executors.newFixedThreadPool(threadNo);
for (int i = 0; i < loop; i++) {
threadPool.submit(new Runnable() {
public void run() { myclass.execTask(); });
}