线程池执行带有自己定义的变量Runnable以及Callable任务时,必须每次都新建任务

问题

public class Test  {
	public static void main(String[] args) throws ExecutionException, InterruptedException  {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
	    BaseCallable callable = new BaseCallable();
	    callable.name = "A";
	    Future<String> future1 = executorService.submit(callable);
	    callable.name = "B";
	    Future<String> future2 = executorService.submit(callable);
	    System.out.println(future1.get());
	    System.out.println(future2.get());
    }
}

class BaseCallable implements Callable<String> {

    public String name;
    
    @Override
    public String call() throws Exception {
        return name;
    }

}

结果

在这里插入图片描述

原因

其结果都为B,由于主线程会比子线程快速执行完,所以两次任务都用到的是同一个变量。

你可能感兴趣的:(并发编程,java,android,开发语言)