我想创建一个同步方法,这样来自该类型线程class的所有对象一次只能访问这个函数。
查看 this web page 时,它说:
An object for which access is to be coordinated is accessed through the use of synchronized methods. These methods are declared with the synchronized keyword. Only one synchronized method can be invoked for an object at a given point in time. This keeps synchronized methods in multiple threads from conflicting with each other.
正如我所说,这不是我想要的,因为我希望能够在类上进行互斥的调用。
最佳答案
要使方法在类(而不是类的特定实例)上同步,请编写:
public static synchronized ReturnType methodName() {
...
}
或
public static ReturnType methodName() {
synchronized(ThisClass.class) {
...
}
}
关于java - 如何同步一组线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12523052/