Created
January 29, 2019 13:27
-
-
Save DesmondFox/30c87184bdaf4b99211b23b1a8aa6774 to your computer and use it in GitHub Desktop.
Using Lock and Condition
(fixed)
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
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Random; | |
import java.util.concurrent.locks.Condition; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReentrantLock; | |
class Account { | |
private int balance; | |
private Lock lock = new ReentrantLock(); | |
private Condition balanceIncreased = lock.newCondition(); | |
public Account(int value) { | |
this.balance = value; | |
} | |
public int getBalance() { | |
return balance; | |
} | |
public void deposite(int value) { | |
lock.lock(); | |
try { | |
balance += value; | |
balanceIncreased.signalAll(); | |
} finally { | |
lock.unlock(); | |
} | |
} | |
public void withdraw(int value) throws InterruptedException { | |
lock.lock(); | |
try { | |
while (balance < value) | |
balanceIncreased.await(); | |
balance -= value; | |
} finally { | |
lock.unlock(); | |
} | |
} | |
} | |
public class Main { | |
public static void main(String... args) throws Exception { | |
Account account = new Account(0); | |
List<Thread> threads = new ArrayList<>(); | |
for (int i = 0; i < 3; i++) { | |
Thread depositThread = new Thread(() -> { | |
try { | |
for (; ; ) { | |
int sum = Math.abs(new Random().nextInt()) % 100; | |
account.deposite(sum); | |
System.out.println("Deposite to acc = " + sum + " from " + Thread.currentThread().getName() + | |
" balance = " + account.getBalance()); | |
Thread.sleep(Math.abs(new Random().nextInt()) % 1000L); | |
} | |
} catch (InterruptedException e) { | |
System.err.println("Interrupted " + Thread.currentThread().getName()); | |
} | |
}, "Deposit thread #" + (i + 1)); | |
depositThread.start(); | |
threads.add(depositThread); | |
} | |
for (int i = 0; i < 2; i++) { | |
Thread withdrawThread = new Thread(() -> { | |
try { | |
for (; ; ) { | |
int sum = Math.abs(new Random().nextInt()) % 1000 + 1000; | |
account.withdraw(sum); | |
System.out.println("Withdraw from acc = " + sum + " from " + Thread.currentThread().getName() + | |
" balance = " + account.getBalance()); | |
} | |
} catch (InterruptedException e) { | |
System.err.println("Interrupted " + Thread.currentThread().getName()); | |
} | |
}, "Withdraw thread #" + (i + 1)); | |
withdrawThread.start(); | |
threads.add(withdrawThread); | |
} | |
Thread.sleep(20000L); | |
for (Thread thr : threads) { | |
thr.interrupt(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment