2 개의 스레드가 있고이 스레드로 Student 개체의 다른 메서드를 실행하려고합니다. 문제는이 코드를 실행하면 t2 스레드가 동기화 된 블록을 완료하기 위해 t1을 기다리는 것입니다.다른 방법으로 다른 개체를 잠그는 방법은 무엇입니까?
t1이 완료 될 때까지 기다리는 이유는 무엇입니까? 어떻게 서로를 차단하지 않고 다른 방법으로 다른 객체를 잠글 수 있습니까?
주요 방법은 다음과 같습니다.
Student student = new Student();
Thread t1 = new Thread(() -> {
try {
student.addA();
} catch (InterruptedException ex) {
Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
}
});
Thread t2 = new Thread(() -> {
try {
student.addB();
} catch (InterruptedException ex) {
Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
}
});
t1.start();
t2.start();
여기는 학생 수업입니다.
public class Student {
private Integer a = 0;
private Integer b = 0;
public void addA() throws InterruptedException{
System.out.println("addA start");
synchronized(a){
System.out.println("addA sync start");
a++;
Thread.sleep(5000);
}
System.out.println("addA end");
}
public void addB() throws InterruptedException{
System.out.println("addB start");
synchronized(b){
System.out.println("addB sync start");
b++;
Thread.sleep(5000);
}
System.out.println("addB end");
}
}