Exercise 7
Exercise 7
a) Write a JAVA program that creates threads by extending Thread class.First thread
display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds
and the third display “Welcome” every 3 seconds,(Repeat the same by implementing
Runnable)
class GoodMorningRunnable implements Runnable {
public void run() {
try {
while (true) {
System.out.println("Good Morning");
Thread.sleep(1000); // 1 second
}
} catch (InterruptedException e) {
System.out.println("Good Morning Runnable Interrupted");
}
}
}
t1.start();
t2.start();
t3.start();
}
}
t1.start();
t2.start();
try {
t1.join(); // Main thread waits for t1 to finish
t2.join(); // Main thread waits for t2 to finish
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
Daemon threads are background threads that automatically terminate when all user threads
(non-daemon threads) finish executing.
In this example, we’ll create a daemon thread that runs continuously in the background,
while a main thread completes after a short time. When the main thread finishes, the daemon
thread also stops automatically.
Output:
Main thread running...
Daemon thread running in background...
Daemon thread running in background...
Daemon thread running in background...
Daemon thread running in background...
Main thread finished. Daemon thread will stop automatically.
In this program:
The Producer will produce a single item and place it in a simple buffer.
The Consumer will take the item from the buffer.
We’ll use wait() and notify() to manage when each can act on the buffer.
class Buffer {
wait();
item = value;
hasItem = true;
wait();
hasItem = false;
return item;
// Producer class
this.buffer = buffer;
int count = 0;
try {
while (true) {
}
} catch (InterruptedException e) {
System.out.println("Producer interrupted");
// Consumer class
this.buffer = buffer;
try {
while (true) {
} catch (InterruptedException e) {
System.out.println("Consumer interrupted");
}
public class SimpleProducerConsumerExample {
Output:
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...