| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
- javascript
- 이펙티브
- 후기
- 알고리즘
- Spring Boot
- JPA
- boot
- 자바스크립트
- 자바
- effective
- Spring
- 맛집
- 인터페이스
- error
- 독후감
- RCP
- jface
- Git
- kibana
- nodejs
- java
- elasticsearch
- java8
- 백준
- node
- MySQL
- 리뷰
- 엘라스틱서치
- Web
- 스프링
- Today
- Total
wedul
synchronized 쓰레드 예제 프로그래밍 본문
문제의 프로그램
package javas;
import javax.swing.JOptionPane;
public class Thread1 {
public static void main(String args[]) {
Runnable r = new RunnableEX();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
class Account{
int balance = 1000;
public void withdraw(int money){
if(balance >= money){
try{ Thread.sleep(1000);}
catch (Exception e){
}
balance -= money;
}
}
}
class RunnableEX implements Runnable{
Account acc = new Account();
public void run(){
while(acc.balance>0){
int money = (int) (Math.random()*3+1)*100;
acc.withdraw(money);
System.out.println("balance : " +acc.balance);
}
}
}
balance를 서로 같이사용하기 때문에 그 부분을 동기화 시켜주지 않았기 때문이다.
해결방법
1. withdraw 메서드 부분을 synchronized 해준다.
public synchronized void withdraw(int money){
if(balance >= money){
try{ Thread.sleep(1000);}
catch (Exception e){
}
balance -= money;
}
}
2. withdraw()가 수행되는 동안 객체에 lock을 걸어준다.
public void withdraw(int money){
synchronized(this){if(balance >= money){
try{ Thread.sleep(1000);}
catch (Exception e){
}
balance -= money;
}
}
}
'JAVA > Thread' 카테고리의 다른 글
| 쓰레드 개념정리 (0) | 2016.12.21 |
|---|---|
| JAVA 데몬 스레드 소개 (1) | 2016.12.21 |
| Thread wait(), notify() 소개 (0) | 2016.12.21 |
| Thread 크리티컬 세션 (0) | 2016.12.21 |
| java thread pool 소개 (0) | 2016.12.21 |
