Chap.14 Android: Synchronization

동기화 (Synchronization)

5. 게임예제, (p.481)

여기서 '동기화' 문제에 신경을 써야한다.   .....

LunarView.java

~~~

synchronized (mSurfaceHolder){

doDraw(c);

}

• Concurrency control

- http://en.wikipedia.org/wiki/Synchronization_(computer_science)

e.g., 두 개의 hwp 프로그램이 '동시에' 하나의 file을 update?

- mutual exclusion → semaphore/lock

http://en.wikipedia.org/wiki/Mutual_exclusion

http://en.wikipedia.org/wiki/Semaphore_(programming)

- 'deadlock' problem

• Java

- 'synchronized' keyword

① 특정 method를 block하는 방식

② 특정 resource(e.g., 객체)를 block하는 방식

// SyncDemo1.java

// #1) 특정 method를 block하는 방식...

public class SyncDemo1 implements Runnable

{

private StringBuffer buf=new StringBuffer();

@Override

public void run(){

printName();

}

//  public void printName(){  // no 'synchronized'...

public synchronized void printName(){

for(int i=0;i<10;i++){

buf.append(Thread.currentThread().getName());

System.out.println(buf.toString());

}

}

public static void main(String[] args){

SyncDemo1 obj=new SyncDemo1();

Thread t0=new Thread(obj, "A");	// Thread Name="A"

Thread t1=new Thread(obj, "B");	// Thread Name="B"

t0.start();

t1.start();

}

}

// SyncDemo2.java

// #2) 특정 resource(e.g., 객체)를 block하는 방식...

public class SyncDemo2 implements Runnable

{

private StringBuffer buf=new StringBuffer();

@Override

public void run(){

printName();

}

public void printName(){

synchronized(buf){

for(int i=0;i<10;i++){

buf.append(Thread.currentThread().getName());

System.out.println(buf.toString());

}

}

}

public static void main(String[] args){

SyncDemo2 obj=new SyncDemo2();

Thread t0=new Thread(obj, "A");	// Thread Name="A"

Thread t1=new Thread(obj, "B");	// Thread Name="B"

t0.start();

t1.start();

}

}