Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 同步块:“同步块”;“期望的表达”;_Java_Android_Intellij Idea_Concurrency - Fatal编程技术网

Java 同步块:“同步块”;“期望的表达”;

Java 同步块:“同步块”;“期望的表达”;,java,android,intellij-idea,concurrency,Java,Android,Intellij Idea,Concurrency,当我使用下面显示的代码时,IntelliJ IDEA会在代码分贝样本中告诉我“expression expected”。这是什么意思,我怎样才能修复它 if (mDecibelSample == null) { synchronized (DecibelSample) { // expression expected if (mDecibelSample == null) { mDecibelSample = new DecibelSample()

当我使用下面显示的代码时,IntelliJ IDEA会在代码
分贝样本中告诉我“expression expected”。这是什么意思,我怎样才能修复它

if (mDecibelSample == null) {
    synchronized (DecibelSample) { // expression expected
        if (mDecibelSample == null) {
            mDecibelSample = new DecibelSample();
        }
    }
}

假设
DecibelSample
是一个类,这不是有效的Java代码

如下所示修改代码以消除编译错误:

synchronized (DecibelSample.class) {}
您的代码无法工作,因为
已同步
需要一些实例来锁定。在上面修改的示例中,它将使用
实例

您还可以将其更改为
synchronized(this){}
,在这种情况下,它将使用您的方法所在的类的实例作为锁

第三个选项是定义用作锁的任意对象,例如:

private static final Object LOCK = new Object();

...

public void foo() {
    synchronized(LOCK) {}
}
这可能是最好的方法,因为锁定当前实例或类实例有一些缺点。有关更多详细信息,请参见:


有关
synchronized
关键字的详细信息,请参见。

同步
关键字需要一个对象<代码>分贝样本
是一个类名,而不是一个对象

对象将用于确保同步:即,当线程需要在同步块内执行代码时:线程必须获取对象上的锁

  • 如果线程可以获得锁,则执行块内的代码并释放锁,以便另一个线程可以获取它

  • 如果无法获取锁:线程将等待锁(由另一个线程拥有)被释放

在您的情况下,需要一个对象来支持锁定机制:

//used for locking only
// don't consume useless memory : a zero-sized array is fine
// ensure that the LOCK is shared between all threads : let's make it static
// ensure that the object used for locking cannot be changed by anyone : let's make it final
// at first sight : we don't need to synchronize on this Object in another class : keep it private.
private static final Object[] LOCK = new Object[0];

  ...
    if (mDecibelSample == null) {
        synchronized (LOCK) {
            if (mDecibelSample == null) {
                mDecibelSample = new DecibelSample();
            }
        }
    }