Last active
January 26, 2019 13:13
-
-
Save DesmondFox/4ed5ef64815e20ab9681bf50d44d3d3e to your computer and use it in GitHub Desktop.
using Atomic types in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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