我試過static
函數和非靜態函數的訪問問題,一個函數是非同步的。如下面的代碼:多線程中的類鎖和對象鎖
public class Resource {
public static synchronized void m1() throws InterruptedException {
System.out.println("Entering m1 method");
Thread.sleep(10000);
System.out.println("Leaving m1 method");
System.out.println();
}
public synchronized void m2() throws InterruptedException {
System.out.println("Entering m2 method");
Thread.sleep(2000);
System.out.println("Leaving m2 method");
System.out.println();
}
public void m3() throws InterruptedException {
System.out.println("Entering m3 method");
Thread.sleep(2000);
System.out.println("Leaving m3 method");
System.out.println();
}
public synchronized void m4() throws InterruptedException {
System.out.println("Entering m4 method");
Thread.sleep(2000);
System.out.println("Leaving m4 method");
System.out.println();
}
}
public class ThreadDemo {
public static void main(String[] args) {
final Resource resource = new Resource();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
resource.m1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
resource.m2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
try {
resource.m3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t4 = new Thread(new Runnable() {
@Override
public void run() {
try {
resource.m4();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t3.start();
t4.start();
}
}
這裏創建了四個線程。
- T1被調用靜態同步(M1)
- T2,T4被調用同步(M2,M4)和
- T3是調用非synnchronized(立方米)。
它的輸出是:
Entering m1 method
Entering m3 method
Entering m2 method
Leaving m3 method
Leaving m2 method
Entering m4 method
Leaving m4 method
Leaving m1 method
我的問題是:
1)靜態同步方法使類級別的鎖。這裏什麼是類級鎖定的含義?如果一個線程已經被鎖定並且類級鎖被佔用,那麼爲什麼線程T2和T3開始執行?
2)T4正在等待完成T2。儘管同步應用於兩種不同的方法,那麼爲什麼T4還要等待呢?如果對象級別鎖定在T2,T4中工作,那麼爲什麼級別鎖定不起作用?