15.임계영역이 여러곳인코드의 동기화
임계영역이 여러곳인 코드의 동기화
- 임계영역이 두개 이상일 경우
public synchronized void load(){
임계영역
만약 여기서 lock을 거는경우 아래에 두번쨰 스레드가 들어갈 수 있을까???
이때 잠금장치: this이므로 먼저 load가 소유해서 두번째 스레드가 기다린다
}
public synchronized void printAll(int count){
메소드에 synchronized를 쓸 경우 문제가 발생!
임계영역
}
키가 같은 경우 흩어져 있어도 다 묶이게 된다 (범위가 넓은 경우에는 바람직하지 않다)
public synchronized void printAll(int count) {
Thread th = Thread.currentThread();
for (int i = 0; i < count; i++) {
StringBuilder builder = new StringBuilder();
builder.append(list);
builder.toString();
System.out.printf("%s[%d-%d]:%s\n", th.getName(), th.getId(), ++index, builder.toString());
}
}
public synchronized void printNext() {
Thread th = Thread.currentThread();
char ch = list[index];
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
return;
}
boolean aquired = indexLock.tryLock();
// synchronized (indexLock) { //
// indexLock.lock();
if (aquired) {
System.out.printf("%s[%d] : index:%d, char: %c\n", th.getName(), th.getId(), index, list[index]);
index++;
indexLock.unlock();
} else {
System.out.printf("%s[%d]: alternater ... \n", th.getName(), th.getId());
}
// }
}
댓글남기기