当我阅读以下示例时,我正在阅读有关并发的教程:
Here are the same two examples as static methods. These methods are synchronized on the class object of the class the methods belong to:
public class MyClass {
public static synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public static void log2(String msg1, String msg2){
synchronized(MyClass.class){
log.writeln(msg1);
log.writeln(msg2);
}
}
}
Only one thread can execute inside any of these two methods at the same time.
Had the second synchronized block been synchronized on a different object than MyClass.class, then one thread could execute inside each method at the same time.
我只是想确保我做对了。
所以你不能在单线程中同时调用方法log1和log2?但如果同步不在类对象上,你可以吗?
我想更多的是翻译让我烦恼。
欢迎提供带有注释的示例。
最佳答案
So you can't call in a single thread the methods log1 and log2 at the same time? But if the synchronized wasn't on the class object you could?
准确地说,您不能在不同线程中同时调用方法log1和log2。声明方法静态同步
与在类对象上同步具有相同的效果。
下面是第二个方法在 log
变量而不是类上同步的示例。
public class MyClass {
public static synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public static void log2(String msg1, String msg2){
synchronized(log){
log.writeln(msg1);
log.writeln(msg2);
}
}
}
在这种情况下,两个单独的线程可以同时执行 log1
和 log2
,因为它们在不同的对象上同步:log1
在 上MyClass.class
对象,以及 log
对象上的 log2
(无论定义在何处)。
以下是有关同步方法和 block 需要记住的关键事项:
- 同步代码必须使用相同的对象实例进行同步 跨所有线程。
- 类也是对象!给定类的对象通常只有一个实例,是在第一次加载该类时创建的。
关于java - 类对象的同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31763379/