我是否需要为每个线程创建新的Callable对象?

joh*_*ohn 2 java multithreading

以下是两个选项

1)创建一个Callable并多次提交

Callable<String> callable = new MyCallable();
        for(int i=0; i< 100; i++){
           Future<String> future = executor.submit(callable);
            list.add(future);
        } 
Run Code Online (Sandbox Code Playgroud)

2)为每个线程创建多个Callables

 for(int i=0; i< 100; i++){
        Future<String> future = executor.submit(new MyCallable());
        list.add(future);
    } 
Run Code Online (Sandbox Code Playgroud)

什么是最佳做法?

dev*_*per 5

如果你MyCallable是线程安全的类,那么你可以重用它的相同实例,否则,你将最终遇到竞争条件和不一致的结果.

换句话说,如果您MyCallable 尝试保留任何未正确同步的状态,则无法使用相同的实例.

例如,在下面的MyCallable类中,您不能跨多个线程重用相同的实例(即,您不能像以前那样共享它executor.submit(singleInstance)):

//Non-Thread Safe Callable implementation
public class MyCallable implements Callable<String> {

    private int i;

    @Override
    public String call() throws Exception {
         i++; //RACE CONDITION
         System.out.println(i);
         return String.valueOf(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您替换int为AtomicInteger,如下所示,那么您可以重用相同的实例:

//Thread Safe Callable implementation
public class MyThreadSafeCallable implements Callable<String> {

    private AtomicInteger i = new AtomicInteger(0);

    @Override
    public String call() throws Exception {
         int value = i.incrementAndGet();
         System.out.println(value);
         return String.valueOf(value);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,这里要注意的重点是,如果你想重用相同的实例Callable,你需要确保它是线程安全的.否则,您需要将多个Callable实例提交给ExecutorService.