我有一个单独的类是这样的:同步方法不会阻止其他线程
private static StringsHandler INSTANCE = null;
private int count = 0;
//I have 2 methods so I don't have to be sending nulls to 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关键字允许多个线程?
你有多个对象吗? –
你怎么称呼它? – bcsb1001
编辑回答您的问题 –