Thread 와 관련이 많은, Synchronized
synchronized 를 사용해보자!
// 메서드에 synchronized 사용
public synchronized void plus(int value){
amount += value;
}
public synchronized void minus(int value){
amount += value;
} public class ModifyAmountThread extends Thread{
private CommonCalculate calc;
private boolean addFlag;
public ModifyAmountThread(CommonCalculate calc, boolean addFlag){
this.calc = calc;
this.addFlag = addFlag;
}
public void run(){
for(int loop = 0; loop<10000; loop++){
if(addFlag){
calc.plus(1);
} else {
calc.minus(1);
}
}
}
}
public class RunSync {
public static void main(String[] args){
RunSync runSync = new RunSync();
runSync.runCommonCalculate();
}
public void runCommonCalculate(){
CommonCalculate calc = new CommonCalculate();
ModifyAmountThread thread1 = new ModifyAmountThread(calc, true);
ModifyAmountThread thread2 = new ModifyAmountThread(calc, true);
thread1.start();
thread2.start();
try{
thread1.join();
thread2.join();
}catch(InterrupedException e){
e.printStackTrace();
}
}
} synchronized 블럭을 사용해보자
Last updated