【发布时间】:2019-12-11 20:57:02
【问题描述】:
这是我的主类,它初始化并启动了 5 个不同的线程:
public class Server implements Runnable {
Server1 server1;
Thread server1Thread;
public Server() {}
@Override
public void run() {
server1 = new Server1();
server1Thread = new Thread(server1);
server1Thread.start();
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
Server s = new Server();
s.run();
}
}
}
这是我的Server1Runnable:
import java.util.concurrent.ConcurrentHashMap;
public class Server1 implements Runnable {
private ConcurrentHashMap<Integer, Integer> storage= new ConcurrentHashMap<>();
public Server1() {}
@Override
public void run() {
synchronized (this){
for (int i = 0; i < 10; i++) {
storage.put(i, (int)(Math.random()*100));
}
for (int i : storage.keySet()) {
System.out.print("(" + i + "," + storage.get(i) + ") ");
}
System.out.println();
}
}
}
它将ConcurrentHashMap storage 键从0 放入9,并在0 和100 之间为它们分配一个随机值。之后它打印它并在最后打印新行。我有用户 synchronized 阻止以确保线程本身正确访问密钥,但它会打印如下内容:
(0,8) (0,87) (1,60) (1,14) (2,20) (2,70) (3,5) (0,74) (0,42) (1,22) (4,96) (0,85) (1,97) (2,75) (3,68) (4,3) (5,49) (6,3) (7,9) (8,47) (9,52)
(3,2) (5,74) (2,86) (1,48) (3,5) (6,0) (4,0) (7,86) (4,22) (8,20) (2,17) (9,87)
(5,96) (5,15) (6,15) (6,92) (7,48) (8,93) (9,67)
(3,87) (7,43) (4,34) (5,48) (8,91) (9,64)
(6,84) (7,75) (8,47) (9,87)
这显然意味着某些线程打印了我分配给它的 10 个以上的键。如何让每个线程准确打印分配给它们的 10 个键和值并确保此处的并发性?
我不确定如何测试它。
【问题讨论】:
-
有50对,键在范围内,随机值随便。所以每个看起来都不错,不是吗?不过,它们同时写入标准输出。
-
我建议尝试
synchronized(System.out)而不是使用synchronized(this)。如果你这样做,你的线程至少会共享同一个锁。 -
线程仅生成 10 个条目。您应该同步跨线程共享的内容。静态键或类本身。这就是这里的问题。
标签: java multithreading concurrency java.util.concurrent concurrenthashmap