java - 如何返回已在 4 个不同线程中编辑过的变量的一个实例?

标签 java multithreading concurrency

好吧,我对标题感到抱歉。我真的不知道该怎么形容这句话。我会在这里做得更好。

所以,我有 2 个 Java 类。我们将它们称为 FirstClassSecondClass (实现 Runnable)。在 FirstClass 中,我正在做一些事情,然后创建 4 个线程。

Thread t1 = new Thread (new SecondClass(s1));
Thread t2 = new Thread (new SecondClass(s2));
Thread t3 = new Thread (new SecondClass(s3));
Thread t4 = new Thread (new SecondClass(s4));

s1s2s3s4 均为 String 类型并持有个人值(value)观。

然后我立即启动线程。

t1.start();
t2.start();
t3.start();
t4.start();

然后在我的 SecondClass 中,我在默认构造函数中获取这些字符串,如下所示

HashMap<String, Integer> map;

public SearchResults(String s) {
    map.put(s, 0);
}

在 run() 方法中我正在执行以下操作

public void run() {
    try {   
        System.out.println(map);
    } catch (Exception e) {
        // TODO: handle exception
    }           
}

所以这个无用程序的结果是 ma​​p 被打印了 4 次,有 4 个不同的值。

我想知道如何返回一个 ma​​p 实例,该实例包含 t1 放入其中的所有值以及 t2 放入其中的所有值> 放入其中等等。他们都在处理相同的变量,ma​​p,但每个线程似乎都做自己的事情。

我可以让线程执行,然后当它们全部完成时,将 ma​​p 返回到另一个类或其他东西吗?我真的对线程了解不多,所以这让我很困惑。任何帮助将不胜感激。

最佳答案

有多种方法可以做到这一点。更好的解决方案是切换并使用 ExecutorService而不是自己 fork 线程。然后您可以实现 Callable<Map> (而不是 Runnable )在您的 SecondClass 中并返回每个作业创建的 map 。

类似于:

// create a thread pool with as many workers as there are jobs
ExecutorService threadPool = Executors.newCachedThreadPool();
List<Future<Map<String, Integer>>> futures =
    new ArrayList<Future<Map<String, Integer>>>();
futures.add(threadPool.submit(new SecondClass(s1)));
futures.add(threadPool.submit(new SecondClass(s2)));
futures.add(threadPool.submit(new SecondClass(s3)));
futures.add(threadPool.submit(new SecondClass(s4)));
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
Map<String, Integer> all = new HashMap<String, Integer>();
for (Future<Map<String, Integer>> future : futures) {
    // future.get() throws an exception if your call method throws
    all.putAll(future.get());
}

那么你的SecondClass实现Callable :

public Map<String, Integer> call() {
    ...
    return map;
}

您可以使用的一些其他机制包括:

  • 使用共享 ConcurrentHashMap传入(更好)或 static (不太好)
  • 让您的线程将其结果放在 BlockingQueue 上当他们完成时
  • 加入线程,然后调用类上的方法来获取 Map就这样被创建了。

关于java - 如何返回已在 4 个不同线程中编辑过的变量的一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15928141/

相关文章:

java - 删除单词中等于单词中最后一个符号的所有符号

非 volatile 对象中的java volatile 对象

java - Java中的形状组合?

java - 使用循环以类似Python的方式连接Java中的数组元素

linux - 在 Linux 中控制信号量队列中的出队顺序

java - AsyncTask vs Thread vs Service(与服务器通信)

session - 在同一个浏览器中拥有两个并发 session 是否有意义?

c# - 仅当满足条件时才从 ConcurrentQueue 中出队

java - 模拟不同窗口中的键盘按下

java - 谁能解释一下线程监视器和等待?