同步方法不会阻止其它线程[关闭]

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

我有一个单例类是这样的:

private static StringsHandler INSTANCE = null;
private int count = 0;
//I have 2 methods so I don't have to be sending/checking nulls on getInstance
//once it's created
public static void createInstance(List<String> strings){
    if(StringsHandler.INSTANCE == null)
        StringsHandler.INSTANCE = new StringsHandler(strings);
}

public static StringsHandler getInstance(){
    return StringsHandler.INSTANCE;
}

public synchronized File use(){
    count++;
    System.out.println("threads using .use " + count);
    while(true){} //Keep the thread here so count should stay as 1
}

实例在应用程序的主类,主方法就这样产生:

if(stringList.isEmpty()){
        LOGGER.error("List was empty");
        System.exit(0);
    }
StringsHandler.createInstance(stringList);

我呼吁使用这样的事情吧:

list.parallelStream().forEach(element -> {
    SingletonClass.getInstance().use();
});

这应该打印threads using .use 1但它打印threads using .use 5为什么synchronized关键字,允许多个线程?

java multithreading java-8 synchronized java-threads
1个回答
2
投票

所述synchronized关键字只允许一个线程来锁定它在其上使用的特定对象。所以,如果你有这个对象的多个实例,并在同一时间拨打use他们的不止一个,他们将能够在同一时间执行。

这是你的责任来决定,并一致地执行,数据元素排除方法的映射。如果不止一个排除法保护的相同数据元素,那么你就不会得到正确的排除。

© www.soinside.com 2019 - 2024. All rights reserved.