Skip to content

Instantly share code, notes, and snippets.

@DesmondFox
Last active January 26, 2019 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DesmondFox/4ed5ef64815e20ab9681bf50d44d3d3e to your computer and use it in GitHub Desktop.
Save DesmondFox/4ed5ef64815e20ab9681bf50d44d3d3e to your computer and use it in GitHub Desktop.
using Atomic types in Java
package com.company;
import java.util.concurrent.atomic.AtomicInteger;
class Account {
private AtomicInteger balance;
Account(int sum) {
balance = new AtomicInteger(sum);
}
public int getBalance() {
return balance.get();
}
public void add(int i) {
balance.addAndGet(i);
}
public void rem(int i) {
balance.addAndGet(-i);
}
}
class Adder implements Runnable {
private final Account acc;
Adder(Account acc) {
this.acc = acc;
}
@Override
public void run() {
for (int i = 0; i < 2000; i++)
acc.add(1);
}
}
class Minuser implements Runnable {
private final Account acc;
Minuser(Account acc) {
this.acc = acc;
}
@Override
public void run() {
for (int i = 0; i < 2000; i++)
acc.rem(1);
}
}
public class Main {
public static void main(String[] args) throws Exception {
Account account = new Account(100_000);
Thread minThr = new Thread(new Minuser(account));
Thread addThr = new Thread(new Adder(account));
System.out.println("Start balance = "+account.getBalance());
System.out.println("Threads ran");
minThr.start();
addThr.start();
minThr.join();
addThr.join();
System.out.println("End balance = "+account.getBalance());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment