작은 혼란이 있습니다. 아래 코드를 살펴보십시오.정적 동기화 방법 및 비 동기화 정적 메서드 혼동
public class ThreadDemo {
//non-static synchronized method
synchronized void a(){
actBusy();
}
//static synchronized method
static synchronized void b(){
actBusy();
}
//static method
static void actBusy(){
try{
Thread.sleep(1000);
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
final ThreadDemo x = new ThreadDemo();
final ThreadDemo y = new ThreadDemo();
Runnable runnable = new Runnable() {
public void run() {
int option = (int) (Math.random() * 4);
switch (option){
case 0: x.a();
break;
case 1: x.b();
break;
case 2: y.b();
break;
case 3: y.b();
break;
}
}
} ;
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
t1.start();
t2.start();
}
}
이 시퀀스를 호출 할 수 있음을 알고 있습니다.
x.a() //in Thread-1
y.b() //in Thread-2
아직도 내가, 우리가 쉽게 x.a()
도 정적 방법이다 actBusy()
방법 호출을 볼 수있는 작은 혼란이 있지만. 메서드 b()
은 동기화되지 않은 정적 메서드를 호출하는 정적 동기화 된 메서드입니다. thread-2가 클래스 레벨 잠금을 얻으면 actBusy()
의 스레드 -1 호출이 차단되지 않습니까?
스레드가 클래스 수준의 잠금을 얻는 경우 다른 클래스 동기화되지 않은 정적 메서드는 다른 메서드 (인스턴스 메서드)에서 호출 할 수 있도록 열린 상태로 유지됩니다. 왜? 비 정적 synchronized
방법은 인스턴스 객체 (this
)에 대한 잠금을 가지고있는 동안
작은 메모이지만'x.a()'와'ThreadDemo.b()'여야합니다. –