最近我读过Bruce Eckel(Thinking in Java),我发现了一些问题:块同步(Object)锁定类!不是这个类的对象。上面提到的代码证明了这一点:
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();
}
}
}
}
我锁定了w2,但锁定得到了w2,!! W1。为什么? w1和w2是不同的对象!他们为什么要锁定在一起?
但所有来源都在讨论锁定同步的OBJECT,而不是Class!如果我误会了,你能帮我理解它是如何运作的吗?
输出
First...1
First...1
First...1
First...1
First...1
First...2
First...2
First...2
First...2
First...2
Second...1
Second...1
Second...1
Second...1
Second...1
Second...2
Second...2
Second...2
Second...2
Second...2
预期输出
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抱歉我的英语(
答案 0 :(得分:0)
<uses-permission android:name="android.permission.INTERNET"/>
表示我们用w2创建一个Lock,而不是锁定对象w2。您可以使用任何其他对象创建锁定,同步块中的代码仍然被锁定。
synchronized (w2)