Question: Rewrite Listing 32.6, ThreadCooperation.java, using the objects wait() and notifyAll() methods. Data from Listing 32.6, 1mport java.util.concurrent.: 2 1mport java.util.concurrent. locks.: 1 3 4 publ1c
Rewrite Listing 32.6, ThreadCooperation.java, using the object’s wait() and notifyAll() methods.
Data from Listing 32.6,


1mport java.util.concurrent.: 2 1mport java.util.concurrent. locks.: 1 3 4 publ1c class ThreadCooperation { private static Account account = new Account (): 5 6 public static void main(String[] args) { II Create a thread pool with two threads ExecutorService executor = Executors.newFixedThreadPool(2): executor.execute(new DepositTask ()): executor.execute(new WithdrawTask ()): executor.shut down (): 7 8 9 10 11 12 13 System.out.printin("Thread 11titThread 21ti tBalance"): 14 15 16 17 public static class DepositTask 1mplements Runnable { e0verride // Keep adding an amount to the account publ1c void run () { try { // Purposely delay it to let the wi thdraw method proceed wh1le (true) { account.deposit((1nt) (Math.random () 10) + 1): Thread.sleep(1000) : 18 19 20 21 catch (InterruptedException ex) { ex . printStackTrace (): 31 publ1c static class Withdraw Task 1mpiements Runnable { e0verride // Keep subtracting an amount from the account publ1c void run () { wh1le (true) ( account.withdraw ( (1nt) (Math.random() 10) + 1); } 32 33 34 35 36 37 38 39 40 I| An inner class for account private static class Account { II Create a new lock private static Lock lock = neN ReentrantLock (): 41 42 43 44 45 /I Create a condition private static Condition newDeposit = lock.newCondition(): 46 47 48 private int balance = 0: 49 50 public int getBalance () { return balance; 51 52 53 54 pub11c void withdraw (1nt amount) { lock. lock (): /I Acquire the lock try { while (balance < amount) { 55 56 57 58
Step by Step Solution
3.50 Rating (167 Votes )
There are 3 Steps involved in it
import javautilconcurrent public class Exercise3208 private static Account account new Account publi... View full answer
Get step-by-step solutions from verified subject matter experts
