Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions practice/synchronized1/CommonCalculate.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
22 changes: 22 additions & 0 deletions practice/synchronized1/ModifyAmountThread.java
Original file line number Diff line number Diff line change
@@ -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);
}
}
}
}
30 changes: 30 additions & 0 deletions practice/synchronized1/RunSync.java
Original file line number Diff line number Diff line change
@@ -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();
}
}
}