简体   繁体   English

用Java中的两个线程打印HashMap的键?

[英]Printing Keys of HashMap with two threads in java?

enter code hereSuppose I have two threads Thread1 and Thread2 and below hashmap with null values. 假设我有两个线程Thread1和Thread2及以下具有空值的hashmap。 Now I want to print the Key of HashMap with respective thread which is executing print statement , without printing it again 现在我想使用正在执行print语句的相应线程来打印HashMap的Key,而无需再次打印它

Input Hashmap: 输入哈希图:

"Hello" null “你好” null

"Customer" null “客户”为空

"Value" null “值”为null

"Bye" null “再见” null

Output: 输出:

"Bye" : Printed by Thread1" “再见”:由线程1打印“

"Hello" :"Printed by Thread2" “ Hello”:“由Thread2打印”

"Value" :"Printed by Thread2" “ Value”:“由Thread2打印”

"Customer" : "Printed by Thread1" “客户”:“由Thread1打印”

So Far I am not able to print with below code. 到目前为止,我无法使用以下代码进行打印。

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test2 implements Runnable {
    volatile static HashMap<String, String> map;

    static Object mutex = new Object();

    static volatile int i = 1;

    public static void main(String[] args) throws InterruptedException {

        map = new HashMap();

        map.put("Public", null);
        map.put("Sort", null);
        map.put("Message", null);
        map.put("Customer", null);
        map.put("Bank", null);
        // ConcurrentHashMap chm= new ConcurrentHashMap(map);

        Collections.synchronizedMap(map);

        Thread t1 = new Thread(new Test2());
        Thread t2 = new Thread(new Test2());
        t1.start();
        t2.start();

    }

    @Override
    public void run() {
        synchronized (mutex) {

            for (Map.Entry entry : map.entrySet()) {

                if (entry.getValue() == null) {
                    System.out.println(entry.getKey() + "\" : \"Printed by " + Thread.currentThread().getName() + '\"');

                    map.put((String) entry.getKey(), Thread.currentThread().getName());

                    if (Thread.currentThread().getName().contains("0")&&i==1) {
                        try {
                            mutex.notifyAll();

                            mutex.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (Thread.currentThread().getName().contains("1")&&i<=1) {
                        try {
                            mutex.notifyAll();
                             i++;
                            mutex.wait();
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                }
            }
            mutex.notifyAll();

        }
    }
}

Just pass each key as a task to an ExecutorService with 2 threads : 只需将每个键作为任务传递给具有2个线程的ExecutorService:

ExecutorService executorService = Executors.newFixedThreadPool(2);

map.keySet().forEach(key -> executorService
   .execute(() -> System.out.println('\"' + key + "\" : \"Printed by " + Thread.currentThread().getName() + '\"')));

executorService.shutdown();
executorService.awaitTermination(5, TimeUnit.SECONDS);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM