java - 当我们说同步(实例字段)时,这意味着什么?

标签 java multithreading object locking synchronized

附上代码.. 这是什么意思,同步(m)..?为什么我们应该使用它..? 同步(this)和同步(m)之间有什么区别..??

class Waiter implements Runnable {

    Message m;

    public Waiter(Message m) {
        this.m = m;
    }

    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (m) {
            try {
                System.out.println("Waiting to get notified at time " +System.currentTimeMillis());
                m.wait();

            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            System.out.println("Waiter thread notified at time "+System.currentTimeMillis());
            System.out.println("Message processed ");
        }
    }
}

最佳答案

synchronized(this)synchronized(m) 之间的区别在于,通过同步 this,您可以同步整个实例。因此,正如您所期望的,当您持有锁时,没有任何主体能够在 this 上进行同步。

public synchronized void foo() {
    // Handle shared resource
}

类似于

public void foo() { 
    synchronize(this) { 
        // Handle shared resource 
    } 
}

通过使用对象,例如m,您可以更精细地控制要同步的内容和时间。但请记住,如果有人使用 foo(),如上所示,它不会停止访问 this 上未同步的方法:

public void anotherLock() {
    synchronized(m) {
        // Should handle another shared resource
        // otherwise you might get unexpected results
    }
}

当一个线程使用 foo() 时,另一个线程可以访问 anotherLock()

关于java - 当我们说同步(实例字段)时,这意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22784209/

相关文章:

java.lang.OutOfMemoryException : java heap space 异常

python - 如何将 `lambda` 对象转换为 `function` 对象以在 Python 中进行酸洗?

java - HQL查询检查表是否有数据

java - 如何在 springboot 2.x 中处理 @pathvariable 中的编码 url(包含特殊字符,如 %2F)?

c++ - 对于 ~95% 写入/5% 读取线程安全的 unordered_map 是否有简单的解决方案?

java - Vert.x事件循环与单线程

c# - 实例化一个类对象并初始化一个列表

javascript - 按属性值(数字键)对 JavaScript 对象进行排序

java - Netbeans 崩溃

Java ExecutorService - 扩展