Updates adder subtractor code.

This commit is contained in:
Tanmay 2022-08-26 15:41:37 +01:00
parent 129277bbed
commit 1387f48f55
3 changed files with 25 additions and 9 deletions

View File

@ -10,7 +10,17 @@ public class Adder implements Runnable {
public void run() { public void run() {
for (int i = 1; i <= 100; ++i) { for (int i = 1; i <= 100; ++i) {
count.getValue().getAndAdd(i);
int value = count.getValue();
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("Something wrong happened");
}
int nextValue = value + i;
count.setValue(nextValue);
try { try {
Thread.sleep(10); Thread.sleep(10);
} catch (Exception e) { } catch (Exception e) {

View File

@ -1,15 +1,13 @@
package com.scaler.addersubtractor; package com.scaler.addersubtractor;
import java.util.concurrent.atomic.AtomicInteger;
public class Count { public class Count {
private AtomicInteger value = new AtomicInteger(0); private volatile int value = 0;
public AtomicInteger getValue() { public int getValue() {
return value; return value;
} }
public void setValue(AtomicInteger value) { public void setValue(int value) {
this.value = value; this.value = value;
} }
} }

View File

@ -1,7 +1,5 @@
package com.scaler.addersubtractor; package com.scaler.addersubtractor;
import java.util.concurrent.locks.Lock;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
@AllArgsConstructor @AllArgsConstructor
@ -12,7 +10,17 @@ public class Subtractor implements Runnable {
public void run() { public void run() {
for (int i = 1; i <= 100; ++i) { for (int i = 1; i <= 100; ++i) {
count.getValue().getAndAdd(-i);
int value = count.getValue();
try {
Thread.sleep(50);
} catch (Exception e) {
System.out.println("Something wrong happened");
}
int nextValue = value - i;
count.setValue(nextValue);
try { try {
Thread.sleep(10); Thread.sleep(10);
} catch (Exception e) { } catch (Exception e) {