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

时间:2017-09-02 21:23:10

标签: java multithreading concurrency hashmap synchronization

在这里输入代码假设我有两个线程Thread1和Thread2,下面的hashmap具有空值。现在我想用正在执行print语句的相应线程打印HashMap的Key,而不再打印它

  

输入Hashmap:

“Hello”null

“客户”为空

“Value”null

“再见”null

  

输出:

“再见”:由Thread1“

打印

“你好”:“由Thread2打印”

“值”:“由Thread2打印”

“客户”:“由Thread1打印”

到目前为止,我无法使用以下代码进行打印。

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();

        }
    }
}

1 个答案:

答案 0 :(得分:2)

将每个密钥作为任务传递给具有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);