在多个线程中同时运行类方法

时间:2019-01-24 21:32:02

标签: java multithreading concurrency

尝试在多个线程中同时运行类方法时遇到问题。

除非实例化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();
    }
}

0 个答案:

没有答案