java语法:“同步(this)"; [英] java syntax: "synchronized (this)"

查看:169
本文介绍了java语法:“同步(this)";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您向我解释这段Java代码?我无法理解这种语法.

can you please explain to me this piece of java code? I cannot understand this syntax.

synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
}

推荐答案

这表示此代码块为synchronized,这意味着最多有一个线程将能够访问该代码块中的代码.

It means that this block of code is synchronized meaning no more than one thread will be able to access the code inside that block.

this表示您可以在当前实例上进行同步(获得对当前实例的锁定).

Also this means you can synchronize on the current instance (obtain lock on the current instance).

这是我在凯西·塞拉(Kathy Sierra)的Java认证书中找到的.

This is what I found in Kathy Sierra's java certification book.

因为同步确实会损害并发性,所以您不想同步 任何比保护您的数据所需的代码更多的代码.因此,如果方法的范围是 您可以将同步零件的范围缩小到超出所需的范围 不到一个完整的方法-只是一个块.

Because synchronization does hurt concurrency, you don't want to synchronize any more code than is necessary to protect your data. So if the scope of a method is more than needed, you can reduce the scope of the synchronized part to something less than a full method—to just a block.

查看以下代码段:

public synchronized void doStuff() {
    System.out.println("synchronized");
}

可以更改为此:

public void doStuff() {
   //do some stuff for which you do not require synchronization
   synchronized(this) {
     System.out.println("synchronized");
     // perform stuff for which you require synchronization
   }
}

在第二个代码段中,同步锁仅应用于该代码块,而不是整个方法.

In the second snippet, the synchronization lock is only applied for that block of code instead of the entire method.

这篇关于java语法:“同步(this)";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆