2016-05-11 134 views
-3

我有一个单独的类是这样的:同步方法不会阻止其他线程

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关键字允许多个线程?

+5

你有多个对象吗? –

+0

你怎么称呼它? – bcsb1001

+0

编辑回答您的问题 –

回答

2

​​关键字只允许一个线程锁定它所使用的特定对象。因此,如果您有多个此对象的实例,并且一次对多个对象调用use,则它们将能够同时执行。

您有责任决定并始终如一地执行数据元素到排除方法的映射。如果有多个排除方法保护相同的数据元素,那么您将无法获得正确的排除。

+0

忘了提及我正在使用单例类,编辑问题。 –

+0

将入口处的对象标识符记录为'use',您会看到它们不是同一个对象。 –

+0

只要'count'没有被声明为'static',仍然不应该有任何线程打印'5'的值。除非有其他代码操纵变量... – Holger

相关问题