1. List the processes (threads) running when you run the application 2. Which on
ID: 3867612 • Letter: 1
Question
1. List the processes (threads) running when you run the application
2. Which one of them are sharing information?
3. What kind of sharing mechanism is being used and how?
import java.util.Date;
import java.lang.*;
public class Factory
{
public static void main(String args[])
{
// creates the message queue
Channel queue = new Channel();
// Creates the producer and consumer threads and pass
Thread producer = new Thread(new Producer(queue));
Thread consumer = new Thread(new Consumer(queue));
// start the threads
producer.start();
consumer.start();
}
}
class Channel {
private Date date;
public void send(Date message){
this.date = message;
}
public Date receive() {
return date;
}
}
class Producer implements Runnable
{
private Channel queue;
public Producer(Channel queue)
{
this.queue = queue;
}
public void run()
{
try
{
Date message;
while (true)
{
// nap for awhile
Thread.sleep(10);
// produces an item and enter it into the buffer
message = new Date();
System.out.println("Producer produced " + message);
queue.send(message);
}
}
catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
}
}
class Consumer implements Runnable{
private Channel queue;
public Consumer(Channel queue)
{
this.queue = queue;
}
public void run()
{
try
{
Date message;
while(true)
{
// nap for awhile
Thread.sleep(10);
// consumes an item from the buffer
message = queue.receive();
if (message != null)
System.out.println("Consumer consumed " + message);
}
}
catch (InterruptedException e) {
System.out.println("I was interrupted!");
}
}
}
Explanation / Answer
1.) The processes that will run when we execute the program are as follows:
These are the two threads that are being used in the above program and it is maintained thoroughly in here.
2.) Both of the threads are sharing information both on the different notes of the program like:
All the sharing of information is been carried out simultaneously in the program and the sharing of the information using the threads is the best thing that could happen to the program.This mkes the code effective and working at the same time. It keeps the program light-wighted.
3.) The mechanism user here for sharing is as follows:
Time Sharing Mechanism:
Hence, this is how the code is using the time sharing mechanism with the help of the threads.
Please rate the answer if it helped.........Thankyou
Hope it helps......
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.