我正在尝试同步访问公共(public)资源(数据库)的类的实例。这可以通过使用notify和wait()来完成,但我需要知道如果不同的java程序使用此类来创建实例,那么如何同步它们。 谢谢
最佳答案
正如 Sotirios Delimanolis 评论的那样 - “你不能。同步只能发生在一个 JVM 的范围内。”
因此,您应该使用一些外部资源来执行此同步。文件可能是一个很好的例子:
try {
// Get a file channel for the file
File file = new File("filename");
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Use the file channel to create a lock on the file.
// This method blocks until it can retrieve the lock.
FileLock lock = channel.lock();
// ** Your logic here **
} finally {
// Release and close
lock.release();
channel.close();
}
关于java - 如何同步不同的java程序访问公共(public)资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19080097/