diff --git a/practice/synchronized1/CommonCalculate.java b/practice/synchronized1/CommonCalculate.java new file mode 100644 index 000000000..dbe5e041f --- /dev/null +++ b/practice/synchronized1/CommonCalculate.java @@ -0,0 +1,28 @@ +package synchronized1; + +public class CommonCalculate { + private int amount; + + public CommonCalculate() { + this.amount = 0; + } + + Object lock = new Object(); + + public void plus(int value) { + // ... + // 10만 줄.... + // ... + synchronized(lock) { + this.amount += value; + } + } + + public void minus(int value) { + this.amount -= value; + } + + public int getAmount() { + return this.amount; + } +} diff --git a/practice/synchronized1/ModifyAmountThread.java b/practice/synchronized1/ModifyAmountThread.java new file mode 100644 index 000000000..0252b2f40 --- /dev/null +++ b/practice/synchronized1/ModifyAmountThread.java @@ -0,0 +1,22 @@ +package synchronized1; + +public class ModifyAmountThread extends Thread { + private CommonCalculate calc; + private boolean addFlag; + + public ModifyAmountThread(CommonCalculate calc, boolean addFlag) { + this.calc = calc; + this.addFlag = addFlag; + } + + @Override + public void run() { + for (int i = 0; i < 10000; i++) { + if (addFlag) { + calc.plus(1); + } else { + calc.minus(1); + } + } + } +} diff --git a/practice/synchronized1/RunSync.java b/practice/synchronized1/RunSync.java new file mode 100644 index 000000000..f3258d637 --- /dev/null +++ b/practice/synchronized1/RunSync.java @@ -0,0 +1,30 @@ +package synchronized1; + +public class RunSync { + + public static void main(String[] args) { + RunSync runSync = new RunSync(); + for (int i = 0; i < 5; i++) { + 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(); + + System.out.println("calc : "+calc.getAmount()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } +}