附上代码.. 这是什么意思,同步(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/