使用ConcurrentHashMap和同步块的Java并发性

问题描述 投票:1回答:2

这是我的主类,它初始化并启动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();
        }
    }
}

这是我的Server1可运行:

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 storage0放入9键,并在0100之间分配一个随机值。之后,将其打印并在最后打印新行。我有用户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个键和值,并确保此处的并发性?

我不确定如何测试。

java multithreading concurrency java.util.concurrent concurrenthashmap
2个回答
0
投票

您的线程不共享任何内部状态。它们工作正常,但是输出是交错的。

例如,如果您使用StringBuilder在一个操作中进行I / O,您应该会看到正确的输出。

        StringBuilder buff = new StringBuilder();
        for (int i : storage.keySet()) {
            buff.append("(" + i + "," + storage.get(i) + ") ");
        }
        System.out.println(buff);

没有充分的理由将Server设置为Runnable,甚至没有创建它的任何实例。

您不共享任何地图。如果您这样做了,那么您也将希望共享一个公共锁,但这不是使用ConcurrentMap的常用方法。


0
投票

您所要做的就是synchronized (Server1.class),因为这在线程之间很常见。不是instance

这里是经过验证的输出:

((0,75)(1,9)(2,61)(3,73)(4,55)(5,34)(6,34)(7,74)(8,41)(9, 0)

((0,30)(1,42)(2,46)(3,66)(4,12)(5,17)(6,62)(7,59)(8,74)(9, 4)

((0,50)(1,16)(2,29)(3,74)(4,68)(5,42)(6,33)(7,91)(8,25)(9, 7)

((0,49)(1,10)(2,39)(3,94)(4,12)(5,55)(6,54)(7,89)(8,21)(9, 75)

((0,77)(1,10)(2,37)(3,32)(4,73)(5,39)(6,64)(7,98)(8,96)(9, 44)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.