Java 'synchronized' method
http://cafe.naver.com/79nana.cafe?iframe_url=/ArticleRead.nhn%3Farticleid=268
class Printer {
synchronized void printChar(char ch) {
for(int i=1; i<=10; i++) {
System.out.print(ch);
}
}
}
class PrinterThread extends Thread {
Printer ptr;
char ch;
PrinterThread(Printer ptr, char ch) {
this.ptr = ptr;
this.ch = ch;
}
public void run() {
for(int i=1; i<=10; i++) {
ptr.printChar(ch);
System.out.println();
}
}
}
public class CSynchronization {
public int m_Start() {
Printer ptr = new Printer();
PrinterThread ptr1 = new PrinterThread(ptr, 'A'); (1)
PrinterThread ptr2 = new PrinterThread(ptr, 'B'); (2)
ptr1.start();
ptr2.start();
return 1;
}
}
(1), (2)에서 동일한 Print 객체를 사용한 것을 확인할 수 있다. 그래야만 하는 듯 하다... 만일 (2)에서 ptr이 아닌 다른 Print객체를 생성하여 넣게 되면 동기화가 정상적으로 진행되지 않는다.