Rewrite Listing 30.6, ThreadCooperation.java, using the object?s wait() and notifyAll() methods. Listing 1 import java.util.concurrent.*; 2 import
Question:
Rewrite Listing 30.6, ThreadCooperation.java, using the object?s wait() and notifyAll() methods.
Listing
Transcribed Image Text:
1 import java.util.concurrent.*; 2 import java.util.concurrent.locks.*; 3 4 public class ThreadCooperation { private static Account account - new Account(O; public static void main(String[] args) { // Create a thread pool with two threads ExecutorService executor = Executors.newFixedThreadPool(2); executor.execute(new DepositTask()); executor.execute(new WithdrawTask ()); executor.shutdown (); 9. 10 11 12 13 14 15 System.out.printIn("Thread 1\t\tThread 2\t\tBalance"); 16 public static class DepositTask implements Runnable { @Override // Keep adding an amount to the account public void run() { try { // Purposely delay it to let the withdraw method proceed while (true) { 17 18 19 20 21 account.deposit((int)(Math.random() * 10) + 1); Thread.sleep(1000); 22 23 24 25 catch (InterruptedException ex) { ex.printStackTrace(); 26 27 28 29 30 31 public static class WithdrawTask implements Runnable { @Override // Keep subtracting an amount from the account public void run() { while (true) { account.withdrawCCint) (Math.random() * 10) + 1); 32 33 34 35 36 37 38 39 40 // An inner class for account 42 private static class Account { // Create a new lock 43 = new ReentrantLock(); 44 private static Lock lock 45 // Create a condition private static Condition newDeposit = lock.newCondition(); 46 47 48 49 50 private int balance = 0; 51 public int getBalance() { return balance; 52 53 54 55 public void withdraw(int amount) { lock.lock(); // Acquire the lock try { while (balance < amount) { 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 72 73 74 75 76 77 78 79 80 81 82 83 System.out.print1n("\t\t\tWait for a deposit"); newDeposit.await(); balance -- amount; System.out.println("\t\t\tWithdraw " + amount + "\t\t" + getBalance ()); catch (InterruptedException ex) { ex.printStackTrace (); finally { lock.unlock (); // Release the lock public void deposit(int amount) { lock.lock(); // Acquire the lock try { balance +- amount; System.out.println("Deposit" + amount + "\t\t\t\t\t" + getBalance()); // Signal thread waiting on the condition newDeposit.signa1A11(); 84 finally { lock.unlock () ; // Release the lock 85 86 87 88 89 90 }
Fantastic news! We've Found the answer you've been seeking!
Step by Step Answer:
Answer rating: 90% (10 reviews)
Program plan Create a new inner class named Account to model the account with two methods depositint and withdrawint The class named DepositTask to ad...View the full answer
Answered By
Ajeet Singh
Professional, Experienced, and Expert tutor who will provide speedy and to-the-point solutions.
I have been teaching students for 5 years now in different subjects and it's truly been one of the most rewarding experiences of my life.
I have also done one-to-one tutoring with 100+ students and help them achieve great subject knowledge.
I have expertise in computer subjects like C++, C, Java, and Python programming and other computer Science related fields.
Many of my student's parents message me that your lessons improved their children's grades and this is the best only thing you want as a teacher. I have done plenty of studying and lots of learning on many exciting and challenging topics. All these experiences have influenced my decision to take on the teaching role in various capacities. As a tutor, I am looking forward to getting to understand your needs and helping you achieve your academic goals. I'm highly flexible and contactable. I am available to work on short notice since I only prefer to work with very small and select groups of students.
4.90+
7+ Reviews
15+ Question Solved
Related Book For
Introduction to Java Programming, Comprehensive Version
ISBN: 978-0133761313
10th Edition
Authors: Y. Daniel Liang
Question Posted:
Students also viewed these Computer science questions
-
Rewrite Listing 18.7, DirectorySize.java, without using recursion. Listing 1 import java.io.File; 2 import java.util.Scanner; 3 4 public class DirectorySize { public static void main(String[] args) {...
-
Rewrite the example shown in Figure 8-4 using Java.
-
Rewrite Programming Exercise using a thread to control the clock animation. Modify Listing, ClockPane.java, to add the animation into this class and add two methods?start()?and?stop()?to start and...
-
Kyrsten Haas expects an S corporation investment to generate a profit of $200,000. Her share of the S corporation is 15%. What is Kyrstens income tax if no cash is distributed? Kyrsten's marginal tax...
-
Explain what might happen if the activation-induced cytidine deaminase (AID) were activated in a cell other than a B cell.
-
The three coupled coils shown in Fig. 14-40 have coupling coefficients of 0.50. Obtain the equivalent inductance between the terminals AB. 200 mH 50 mH 100 mH B
-
Founded in 1966 as a trader of oil and oil products, Vitol is a company with no external shareholders. All shareholders are also employees. It is a conglomerate company of energy companies that work...
-
The Sabat Corporation manufactures and sells two products: Thingone and Thingtwo. In July 2013, Sabats budget department gathered the following data to prepare budgets for 2014: 2014 Projected Sales...
-
Brae Industries Inc. purchased a machine on January 2, 2020, with a cost of $175,000, with an expected useful life of five (5) years, and an estimated salvage value of $8,000. Brae depreciates all...
-
Journalize the transactions: Cash Receipt #1522 Dated April 4, 2022 From Nikki Chow, cheque #183 for $1 450 in full payment of invoice #1104, taking into account 2% sales discount of $50 for early...
-
Listing 15.17 BallPane.java using a thread to animate bouncing ball movements. Listing 1 import javafx.animation.KeyFrame; 2 import javafx.animation.Timeline; 3 import...
-
The iterator is failfast. Write a program to demonstrate it by creating two threads that concurrently access and modify a set. The first thread creates a hash set filled with numbers, and adds a new...
-
The data in Exercise 4 were generated using the following functions. Use the cubic splines constructed in Exercise 4 for the given value of x to approximate f (x) and f'(x), and calculate the actual...
-
Morgan Inc. manufactures ergonomically correct office chairs. They have a contribution margin of $110,000 and fixed expenses of $28,500. They are adding a warehouse space that will add $20,000 to...
-
Building an active portfolio. In this problem, we will build an active portfolio, that is, a portfolio consisting of individually selected stocks to complement our passive investments. To do this,...
-
On January 1, 2022, Contreras Corporation purchases 10,000 shares of Home Depot stock for $280 per share. Home Depot had approximately 1 billion shares outstanding at the time of purchase. Contreras...
-
The inability of a pilot to carry out the duties required to fly an aircraft is sometimes called _________. orientation incapacitation discombobulation alienation
-
B&e inc. acquired a registered trademark for $800,000 with a remaining legal life of four years. however, it can be renewed every 10 years. b&e expects to renew the trademark indefinitely. what...
-
Yolanda and Xavier, spouses, have four adult children, Andy, Betty, Cathy, and Danny. In 2014, they made a number of gifts. Yolanda gave Andy cash of $40,000 and Betty stock valued at $60,000. Xavier...
-
Write out the formula for the total costs of carrying and ordering inventory, and then use the formula to derive the EOQ model. Andria Mullins, financial manager of Webster Electronics, has been...
-
How arc different RTP streams in different sessions identified by a receiver? How are different streams from within the same session identified?
-
Consider the figure below (which is similar to Figure 9.3). A sender begins sending packetized audio periodically at t = 1. The first packet arrives at the receiver at t = 8. Figure 9.3 a. What are...
-
Why is a packet that is received after its scheduled play out time considered lost?
-
After the U.S. Congress passed temporary tax cuts in 2010, U.S. taxpayers who earned up to $50,000 per year had a lower tax rate. On average, these taxpayers retained 2% more of their income than...
-
At the beginning of the year DRJ Enterprises reported gross fixed assets of $915 million and net fixed assets of $616 million; at the end of the year, it reported gross fixed assets of $882 million...
-
In 20X2, Jacque's Gardening Supply acquired Glenn's Agricultural Center and recorded goodwill in the amount of $450,000. At the end of the 20X4 year, the net assets (including goodwill) of Glenn's...
Study smarter with the SolutionInn App