#19 was : thread safe

This commit is contained in:
haerong22
2022-09-05 03:02:14 +09:00
parent f45ed023c5
commit a5320f4fbc
2 changed files with 43 additions and 0 deletions

View File

@@ -0,0 +1,28 @@
package org.example.counter;
public class Counter implements Runnable {
private int count = 0;
public void increment() {
count++;
}
public void decrement() {
count--;
}
public int getValue() {
return count;
}
@Override
public void run() {
synchronized (this) {
this.increment();
System.out.println("Value for Thread After increment " + Thread.currentThread().getName() + " " + this.getValue());
this.decrement();
System.out.println("Value for Thread at Last " + Thread.currentThread().getName() + " " + this.getValue());
}
}
}

View File

@@ -0,0 +1,15 @@
package org.example.counter;
public class RaceConditionDemo {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(counter, "Thread-1");
Thread t2 = new Thread(counter, "Thread-2");
Thread t3 = new Thread(counter, "Thread-3");
t1.start();
t2.start();
t3.start();
}
}