尝试在多个线程中同时运行类方法时遇到问题。
除非实例化myClass.thisMethodWillBeRanMultipleTimes()
时创建对象myClass
的副本,否则不会执行对MyRunnable
的调用。
public class MyClass {
public MyClass() {
}
public Object thisMethodWillBeRanMultipleTimes() {
Object anObject;
...
// do something
...
return anObject;
}
}
public class SampleExecutorService {
private static final int MYTHREADS = 3;
public static void main(String args[]) throws Exception {
MyClass myClass = new MyClass();
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
Runnable worker1 = new MyRunnable(myClass);
executor.execute(worker1);
Runnable worker2 = new MyRunnable(myClass);
executor.execute(worker2);
Runnable worker3 = new MyRunnable(myClass);
executor.execute(worker3);
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println("\nFinished all threads");
}
}
public class MyRunnable implements Runnable {
private MyClass myClass;
MyRunnable(MyClass myClass) {
this.myClass = myClass;
}
@Override
public void run() {
Object someObject = myClass.thisMethodWillBeRanMultipleTimes();
}
}