Syncronized 목적 :
Thread Safe 언제 문제가 발생하는가?
-> 여러 쓰레드가 한 객체에 선언된 변수에 접근하는 경우
-> 단 메소드에서 인스턴스 변수를 "수정"하려 하는 때만 발생. 어떻게
-> 메소드 자체를 syncronized로 선언 (syncronized method)
-> 특정 문장만 선언(syncronized statements) sycrhonized 블록을 사용
-> 참조해야할 변수가 여러 개 인 경우, 각 참조할 객체마다 다른 Syncronized block을 만들어 준다.
(예제 참조)
ex)
package com.test.testapplication;
public class TestApplication {
public static void main(String [] args) {
TestApplication test = new TestApplication();
test.doTest();
}
//각 쓰레드에서 참조할 변수
public int count ;
public int timeCount ;
private void doTest() {
count=0;
ThreadSample t1= new ThreadSample("t1");
ThreadSample t2= new ThreadSample("t2");
t1.start();
t2.start();
/*
* try { Thread.sleep(10000); } catch (InterruptedException e) {
*
* System.out.println( e.toString() ); e.printStackTrace(); }
*/
//tip : thread 종료를 기다리도록 join method 사용
try {
t1.join();
t2.join();
}catch(InterruptedException e ) {
e.printStackTrace();
}
System.out.println("final count : " + count);
System.out.println("final timecount : " + timeCount);
}
/*참조해야할 변수가 여러개일 경우 , 서로 다른 lock을 사용한다.*/
private Object lock = new Object();
private Object timeCountLock = new Object();
class ThreadSample extends Thread{
public ThreadSample(String name) {
super(name);
}
@Override
public void run() {
int loop = 0;
while( loop < 10) {
++loop;
synchronized(lock) {
System.out.println( this.getName() + " run!" + " count : "+(count++));
}
synchronized(timeCountLock) {
System.out.println( this.getName() + " run!" + " timeCount : "+(timeCount++));
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println( e.toString() );
e.printStackTrace();
}
}
}
/*
* @Override public void run() { synchronizedRun(); }
*/
}
// 각 쓰레드에서 공통으로 참조하는 method에 synchronized 선언을 해준다.
public synchronized void synchronizedRun() {
int loop = 0;
while( loop < 10) {
++loop;
System.out.println( getClass().getSimpleName() + " run!" + " count : "+(count++));
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println( e.toString() );
e.printStackTrace();
}
}
}
}
'java' 카테고리의 다른 글
| FileFilter , FileNameFilter interface (0) | 2019.09.21 |
|---|---|
| Thread interrupt 및 getState 예제 (0) | 2019.09.21 |
| Thread Priority 와 Daemon Thread (0) | 2019.09.17 |
| Runnable interface와 Thread class (0) | 2019.09.17 |
| Simple HashSet 및 Iterator 사용 예제 (0) | 2019.09.16 |