Answered step by step
Verified Expert Solution
Question
1 Approved Answer
User import java.util.ArrayList; import java.util.List; class Producer implements Runnable { private final List buffer; public Producer ( List buffer ) { this.buffer = buffer; }
User
import java.util.ArrayList; import
java.util.List;
class Producer implements Runnable
private final List buffer;
public ProducerList buffer
this.buffer buffer;
@Override
public void run
String names firstdose", "seconeddose", "boosterdose";
for String name : names
synchronized buffer
buffer.addname;
try
Thread.sleep;
catch InterruptedException e
System.out.printlnThreadcurrentThreadgetName add to list name;
System.out.printlnThreadcurrentThreadgetName exit Main.finish;
synchronized buffer buffer.addMainfinish;
class Consumer implements Runnable
private final List buffer; public
ConsumerList buffer
this.buffer buffer;
@Override
public void run while
true synchronized
buffer
if bufferisEmpty
continue;
if buffergetequalsMainfinish
System.out.printlnThreadcurrentThreadgetName exiting.";
break;
else
System.out.printlnThreadcurrentThreadgetName remove from list
buffer.remove;
System.out.println;
try create thread for consumer
Thread.sleep;set the delay for one seconed
catch InterruptedException e
public class Main
public static final String finish "finish"; end the process
public static void mainString args
List buffer new ArrayList; buffer we used Thread
Thread producerThread new Threadnew Producerbuffer;
producerThreadsetNameproducer Thread ;
Thread producerThread new Threadnew Producerbuffer;
producerThreadsetNameproducer Thread ;
Thread consumerThread new Threadnew Consumerbuffer;
consumerThreadsetNameconsumer Thread ;
Thread consumerThread new Threadnew Consumerbuffer;
consumerThreadsetNameconsumer Thread ;
producerThreadstart;
producerThreadstart;
consumerThreadstart;
consumerThreadstart;
this is the output
producer Thread add to list firstdose
consumer Thread remove from list firstdose
producer Thread add to list firstdose
consumer Thread remove from list firstdose
producer Thread add to list seconeddose
consumer Thread remove from list seconeddose
producer Thread add to list seconeddose
consumer Thread remove from list seconeddose
producer Thread add to list boosterdose
consumer Thread remove from list boosterdose
producer Thread exit finish
producer Thread add to list boosterdose
producer Thread exit finish
consumer Thread remove from list boosterdose
consumer Thread exiting.
consumer Thread exiting. ineed same this output rewrite this code i need same output
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started