Java 쓰레드의 동기화(synchronization)
by 볼빵빵오춘기쓰레드의 동기화(synchronization)
- 멀티 쓰레드 프로세스에서는 다른 쓰레드의 작업에 영향을 미칠 수 있다.
- 진행중인 작업이 다른 쓰레드에게 간섭하지 않게 하려면 ‘동기화’가 필요하다.
⇒ 쓰레드의 동기화 : 한 쓰레드가 진행중인 작업을 다른 쓰레드가 간섭하지 못하게 막는 것 - 동기화하려면 간섭받지 않아야 하는 문장들을 ‘임계 영역’으로 설정해야 한다.
- 임계영역은 락(lock)을 얻은 단 하나의 쓰레드만 출입가능하다.(객체 1개에 락1개)
synchronized를 이용한 동기화

예제

예제 코드
import javax.swing.JOptionPane; public class Try { static long startTime = 0; public static void main(String[] args) { Runnable r = new RunnableEx12(); new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다. new Thread(r).start(); // ThreadGroup에 의해 참조되므로 gc대상이 아니다. } } class Account { private int balance = 1000; public int getBalance() { return balance; } public void withdraw(int money){ if(balance >= money) { try { Thread.sleep(1000);} catch(InterruptedException e) {} balance -= money; } } // withdraw } class RunnableEx12 implements Runnable { Account acc = new Account(); public void run() { while(acc.getBalance() > 0) { // 100, 200, 300중의 한 값을 임으로 선택해서 출금(withdraw) int money = (int)(Math.random() * 3 + 1) * 100; acc.withdraw(money); System.out.println("balance:"+acc.getBalance()); } } // run() }
결과1

결과2

⇒ 결과값이 계속 달라진다.
⇒ 한 줄 출력된후 다음 한 줄 출력된다.

블로그의 정보
Hello 춘기's world
볼빵빵오춘기