#19 was : thread safe
This commit is contained in:
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user