Having problems trying to run a class method concurrently in multiple threads.
The call to myClass.thisMethodWillBeRanMultipleTimes()
does not execute unless I create a copy of the object myClass
when I instantiate 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();
}
}