Question: I am getting the error, unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(10);. I think I need to write a try

I am getting the error, unreported exception InterruptedException; must be caught or declared to be thrown Thread.sleep(10);. I think I need to write a try and catch but I'm not sure how and where to put it.

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() { 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);

}

} }

class Consumer implements Runnable{ private Channel queue;

public Consumer(Channel queue) { this.queue = queue;

} public void run() { 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);

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Youre encountering the InterruptedException error because the Threadsleeplong millis method in Java can throw this exception and it must either be cau... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!