Java同步锁定类,而不是对象?
最近我读了Bruce Eckel(用Java思考),发现了一些问题:块同步(对象)锁定类!不是这个类的对象。本规范证明了上述内容:Java同步锁定类,而不是对象?,java,multithreading,concurrency,synchronized,java.util.concurrent,Java,Multithreading,Concurrency,Synchronized,Java.util.concurrent,最近我读了Bruce Eckel(用Java思考),发现了一些问题:块同步(对象)锁定类!不是这个类的对象。本规范证明了上述内容: public class Main { public static void main(String[] args) { Sync s = new Sync(); new Thread(new Runnable() { @Override public void run() {
public class Main {
public static void main(String[] args) {
Sync s = new Sync();
new Thread(new Runnable() {
@Override
public void run() {
s.go();
}
}, "First").start();
new Thread(new Runnable() {
@Override
public void run() {
s.go();
}
}, "Second").start();
}
}
class Sync {
private Writer w1, w2;
public Sync() {
w1 = new Writer();
w2 = new Writer();
}
public void go() {
synchronized (w2) {
w1.log(Thread.currentThread().getName() + "...1");
//!All threads must performance parallel, but they do it consistently.
w2.log(Thread.currentThread().getName() + "...2");
//All threads must performance parallel, and they do it.
}
}
}
class Writer {
public void log(Object obj) {
for (int i = 0; i < 5; i++) {
lgn(obj);
try {
TimeUnit.MILLISECONDS.sleep(750);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
预期产量
First...1
Second...1
First...1
Second...1
First...1
Second...1
First...1
Second...1
First...1
Second...1
First...2
First...2
First...2
First...2
First...2
Second...2
Second...2
Second...2
Second...2
Second...2
p.S对不起我的英语(synchronized(w2)
表示我们使用w2创建锁,而不是锁定对象w2。您可以使用任何其他对象创建锁,并且同步块中的代码仍然被锁定
class Sync {
private Writer w1, w2;
private Object whatEver;
public Sync() {
w1 = new Writer();
w2 = new Writer();
whatEver = new Object();
}
public void go() {
synchronized (whatEver) {
w1.log(Thread.currentThread().getName() + "...1");
//!All threads must performance parallel, but they do it consistently.
w2.log(Thread.currentThread().getName() + "...2");
//All threads must performance parallel, and they do it.
}
}
}
请用英语回答。我投票将这个问题作为离题题结束,因为它属于我翻译过的)看起来你锁定了Writer w2
synchronized(w2)
并没有阻止另一个线程与w2
:它阻止另一个线程进入相同的synchronized(w2)
块。(注意:它还会阻止其他线程进入任何其他synchronized(w2)
块,但在您的示例中,您只有一个这样的块。)
class Sync {
private Writer w1, w2;
private Object whatEver;
public Sync() {
w1 = new Writer();
w2 = new Writer();
whatEver = new Object();
}
public void go() {
synchronized (whatEver) {
w1.log(Thread.currentThread().getName() + "...1");
//!All threads must performance parallel, but they do it consistently.
w2.log(Thread.currentThread().getName() + "...2");
//All threads must performance parallel, and they do it.
}
}
}