我必须同时执行我的类的多个实例。我在下面编写了以下代码。我已经通过两种方式做到了。但我看不出有什么区别。并行运行线程的正确方法是什么?
谢谢。
这里的片段:
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(){
.........
}
}
}