다음과 같은 코드로 인해 동기화 된 메소드가 만들어 지지만 객체 레벨 잠금이 발생하는 이유를 설명 할 수 있습니까? 자바 동시성을 철저히 따릅니다. 클래스 레벨을 사용하면 확실히 작동하므로 스레드마다 차지하는 잠금이 서로 다르기 때문에 설명하십시오.자바 동시성 동기화 문제
/**
*
*/
package lession2.shared.object;
/**
* @author so_what
*
*/
class SharedClass {
private static int sharedData;
public synchronized int getSharedData() {
return sharedData;
}
public synchronized void setSharedData(int sharedData) {
SharedClass.sharedData = sharedData;
}
}
//output of the program should be the distinct numbers
public class StaleDataExample extends Thread {
static SharedClass s1=new SharedClass();
static int counter=0;
public static void main(String args[]) throws InterruptedException {
StaleDataExample t1=new StaleDataExample();
StaleDataExample t2=new StaleDataExample();
StaleDataExample t3=new StaleDataExample();
StaleDataExample t4=new StaleDataExample();
StaleDataExample t5=new StaleDataExample();
StaleDataExample t6=new StaleDataExample();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
t6.join();
System.out.println();
}
public void run()
{
s1.setSharedData(s1.getSharedData()+1); //read->modify->write operation
System.out.print(s1.getSharedData()+" ");
}
}
'// 읽기> 수정 -> 쓰기 작업'은'읽기'와'쓰기'만이 (독립적으로) 동기화됩니다. 단일 원자 조작이어야합니다. – tkausl
get과 set 작업이 동일한 잠금 복합 원자량을 획득하는 경우 동일한 잠금을 획득하지 않는 이유를 정당화 할 수 있습니까? –
그들은 같은 잠금을 획득하고 있습니다. 왜냐하면 다른 잠금 스레드가 개입 할 수있는 값을 전혀 수정하지 않는 타임 슬라이스가 존재하기 때문입니다. – tkausl