用java中的两个线程打印HashMap的键?
在这里输入代码假设我有两个线程Thread1和Thread2以及以下hashmap与null值。现在我想打印的HashMap与正在执行打印语句各自线程的关键,而无需再次打印出来用java中的两个线程打印HashMap的键?
输入的Hashmap:
“你好”空
“客户”空
“值” 空
“再见” 空
输出:
“再见”:由线程1" 印刷
“你好”: “由线程2印刷”
“值”: “由线程2印刷”
“客户”:“由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();
}
}
}
只是通过每个键的任务的ExecutorService的2个线程:
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);
任何方式来摆脱线程名池名称? –
@RaviGodara当然:使用'newFixedThreadPool'方法,它接受一个'ThreadFactory'作为第二个参数,并传递一个给你的喜好的线程。 – bowmore
这很有效,还有一个问题,为什么Executor服务表现线程安全?不同于分别创建两个线程。 –
而问题是什么? – Kamil
无法找到按键应该打印一次的方法。 @Kamil –
将键收集到一个列表中,将它分成两部分,将前半部分传递给第一个线程,将第二部分传递给第二个线程,启动两个线程?我不知道你为什么要这样做,但你可以。如果你想用多线程练习,你应该找到一个更现实,更有用的用例。 –