차단 동작은 리플렉션없이 해당 메서드를 호출 할 때와 완전히 동일합니다. 기본적으로 아래의 JVM은 동일한 로직을 실행합니다. 아래의 코드와 함께 스스로를 시도 할 수 있습니다 : 인쇄에서
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SynchronizedReflectionTest {
public static void main(String[] args) {
SynchronizedReflectionTest test = new SynchronizedReflectionTest();
for(int i=0; i<5; i++) {
final int finalI = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
Method someThing = SynchronizedReflectionTest.class.getDeclaredMethod("someThing", new Class[]{int.class});
someThing.invoke(test, finalI);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}).start();
}
}
public synchronized void someThing(int nr)
{
System.out.println("Executing someThing from "+nr);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished executing from nr "+nr);
}
}
는 해당 메서드 호출이 동기화 볼 수 있습니다 발생합니다. 인쇄 결과 : 완전히 안전하고 쓸모없는 것 메소드 호출 반사 메커니즘의 유형에서 따라 달라집니다 경우 잠금 지키고 코드가 동기화 블록에서 실행하고 것
Executing someThing from 0
Finished executing from nr 0
Executing someThing from 4
Finished executing from nr 4
Executing someThing from 3
Finished executing from nr 3
Executing someThing from 2
Finished executing from nr 2
Executing someThing from 1
Finished executing from nr 1
JVM 보증.
리플렉션을 사용하는 경우 리플렉션 코드는 또한 스레드에 있습니다. –