Programming Language/Java
스레드(Thread) - 5. Thread 동기화
NewBean
2022. 7. 15. 18:18
Ⅴ. Thread 동기화
1. 동기화(synchronized)
// Example
package sample;
// 순차적인 동작을 처리할 때, 싱크가 맞지 않는 부분을 고쳐보자
// → synchronized 키워드 적용
class Counter {
private int count = 0;
// 메소드 간의 동기화가 이루어짐.
// 따라서 다른 메소드의 동작 시, 침범하지 않고 기다림
public void increment() {synchronized(this) {count++;}}
public void decrement() {synchronized(this) {count--;}}
public int getCount() {return count;}
}
public class Main {
static Counter a = new Counter(); // main은 스태틱메모리라서 스태틱을 추가
static class Incre implements Runnable {
public void run() {
for(int i = 0; i < 1000; i++) {
a.increment();
}
}
}
static class Decre implements Runnable {
public void run() {
for(int i = 0; i < 1000; i++) {
a.decrement();
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Incre());
Thread t2 = new Thread(new Decre());
t1.start();
t2.start();
// 스레드의 동작이 오래걸릴 경우를 대비하는 방법
// join() : 스레드가 작업을 끝날 때까지 프로세스가 안 끝나게 함
try {
t1.join();
t2.join();
} catch(Exception e) {
e.printStackTrace();
}
System.out.println(a.getCount()); // 0
}
}