爲什麼兩個同步塊不能由Java中的兩個不同線程同時執行。在Java中執行兩個同步塊
編輯
public class JavaApplication4 {
public static void main(String[] args) {
new JavaApplication4();
}
public JavaApplication4() {
Thread t1 = new Thread() {
@Override
public void run() {
if (Thread.currentThread().getName().equals("Thread-1")) {
test(Thread.currentThread().getName());
} else {
test1(Thread.currentThread().getName());
}
}
};
Thread t2 = new Thread(t1);
t2.start();
t1.start();
}
public synchronized void test(String msg) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
System.out.println(msg);
}
}
public synchronized void test1(String msg) {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
System.out.println(msg + " from test1");
}
}
}
如果它們在不同的對象上同步,它們可以。如果它們在同一個對象上同步,那麼同時執行就會失敗目的。 – Keppil 2012-08-10 11:46:56
我懷疑你有更深的擔憂。你能改說你的問題嗎? – 2012-08-10 11:50:40
@Keppil請檢查EDIT部分 – 2012-08-10 11:51:18