Android(Java)
[Java]Runnable / Lock 동기화 기초
삽질중
2024. 1. 12. 13:36
참고사이트 : https://zion830.tistory.com/57
멀티스레드 사용시 동시성 문제가 발생하기 마련이다. 간단한 예제를 통해서 동기화 방법을 알아본다.
class SharedData {
private int value;
public void increase() {
value += 1;
}
public void print() {
System.out.println(value);
}
}
Runnable 클래스
public class TestRunnable implements Runnable {
private final SharedData myShardData;
public TestRunnable(SharedData myShardData) {
this.myShardData = myShardData;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
myShardData.increase();
}
myShardData.print();
}
}
Activity에서 실행
public void onRunnableStart(View v) {
final SharedData mySharedData = new SharedData();
for (int i = 0; i < 100; i++) {
new Thread(new TestRunnable(mySharedData)).start();
}
}
실행결과 : 순서대로 나오는것 아니라 뒤섞여서 결과값이 나온다.
I/System.out: 100
I/System.out: 200
I/System.out: 300
I/System.out: 400
I/System.out: 500
I/System.out: 700
I/System.out: 1200
I/System.out: 1600
I/System.out: 2000
I/System.out: 2400
I/System.out: 1100
Runnable 클래스에 Lock 적용
public class TestRunnable implements Runnable {
private final Lock lock;
private final SharedData myShardData;
public TestRunnable(SharedData myShardData, Lock lock) {
this.myShardData = myShardData;
this.lock = lock;
}
@Override
public void run() {
lock.lock();
try {
for (int i = 0; i < 100; i++) {
myShardData.increase();
}
myShardData.print();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
Activity에서 실행
public void onRunnableStart(View v) {
final SharedData mySharedData = new SharedData();
final Lock lock = new ReentrantLock();
for (int i = 0; i < 100; i++) {
new Thread(new TestRunnable(mySharedData, lock)).start();
}
}
실행결과 : 순차적으로 동기화 되서 표시됨.
I/System.out: 100
I/System.out: 200
I/System.out: 300
I/System.out: 400
I/System.out: 500
I/System.out: 600
I/System.out: 700
I/System.out: 800
I/System.out: 900
I/System.out: 1000