Java,Thread - 同步变量

时间:2013-09-09 13:57:17

标签: java multithreading variables synchronization

如何在线程之间创建公共变量? 例如:许多线程向服务器发送请求以创建用户。

这些用户保存在ArrayList中,但必须为所有线程同步此ArrayList。我该怎么办?

全部谢谢!

3 个答案:

答案 0 :(得分:4)

如果要从多个线程访问列表,可以使用Collections来包装它:

List<String> users = Collections.synchronizedList(new ArrayList<String>());

然后简单地将它在构造函数中传递给将使用它的线程。

答案 1 :(得分:3)

我会使用ExecutorService并向您要执行的任务提交任务。这样您就不需要同步集合(可能根本不需要集合)

但是,您可以通过创建一个包含Collections.synchronizedList()的ArrayList来执行您的建议,并在启动它之前将其作为对该线程的引用传递。

你能做的就像是

// can be reused for other background tasks.
ExecutorService executor = Executors.newFixedThreadPool(numThreads);

List<Future<User>> userFutures = new ArrayList<>();
for( users to create )
   userFutures.add(executor.submit(new Callable<User>() {
        public User call() {
            return created user;
        }
   });
List<User> users = new ArrayList<>();
for(Future<User> userFuture: userFutures)
   users.add(userFuture.get();

答案 2 :(得分:1)

要扩展@ Peter的答案,如果您使用ExecutorService,则可以提交Callable<User>,该User可以返回由另一个线程中运行的任务创建的// create a thread pool with 10 background threads ExecutorService threadPool = Executors.newFixedThreadPool(10); List<Future<User>> futures = new ArrayList<Future<User>>(); for (String userName : userNamesToCreateCollection) { futures.add(threadPool.submit(new MyCallable(userName))); } // once you submit all of the jobs, we shutdown the pool, current jobs still run threadPool.shutdown(); // now we wait for the produced users List<User> users = new ArrayList<User>(); for (Future<User> future : futures) { // this waits for the job to complete and gets the User created // it also throws some exceptions that need to be caught/logged users.add(future.get()); } ... private static class MyCallable implements Callable<User> { private String userName; public MyCallable(String userName) { this.userName = userName; } public User call() { // create the user... return user; } }

类似的东西:

{{1}}