mirror of
https://github.com/robindhole/fundamentals.git
synced 2025-03-15 23:19:56 +00:00
Uses atomic integers for adder and subtractor.
This commit is contained in:
parent
72a8af8382
commit
bae1f04a21
@ -0,0 +1,22 @@
|
||||
package com.scaler.addersubtractor;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
@AllArgsConstructor
|
||||
public class Adder implements Runnable {
|
||||
private Count count;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
count.getValue().getAndAdd(i);
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Something wrong happened");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,15 @@
|
||||
package com.scaler.addersubtractor;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class Count {
|
||||
private AtomicInteger value = new AtomicInteger(0);
|
||||
|
||||
public AtomicInteger getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(AtomicInteger value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
@ -0,0 +1,27 @@
|
||||
package com.scaler.addersubtractor;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class Runner {
|
||||
public static void main(String[] args) {
|
||||
Count count = new Count();
|
||||
|
||||
Adder adder = new Adder(count);
|
||||
Subtractor subtractor = new Subtractor(count);
|
||||
|
||||
ExecutorService executor = Executors.newCachedThreadPool();
|
||||
executor.execute(adder);
|
||||
executor.execute(subtractor);
|
||||
|
||||
executor.shutdown();
|
||||
try {
|
||||
executor.awaitTermination(100, TimeUnit.SECONDS);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Something wrong happened");
|
||||
}
|
||||
|
||||
System.out.println(count.getValue());
|
||||
}
|
||||
}
|
@ -0,0 +1,28 @@
|
||||
package com.scaler.addersubtractor;
|
||||
|
||||
import java.util.concurrent.locks.Lock;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
|
||||
@AllArgsConstructor
|
||||
public class Subtractor implements Runnable {
|
||||
private Count count;
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
for (int i = 1; i <= 100; ++i) {
|
||||
count.getValue().getAndAdd(-i);
|
||||
try {
|
||||
Thread.sleep(10);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Something wrong happened");
|
||||
}
|
||||
|
||||
for (int j = 0; j < 10000; ++j) {
|
||||
// do something
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user