unit 3
unit 3
unit 3
PROGRAM:
try {
} catch (InterruptedException e) {
System.out.println(e);
OUTPUT:
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
The output consists of the lines "Thread: 1", "Thread: 2", etc., printed in sequence. The output
order may vary depending on thread scheduling by the JVM.
Class Declaration:
class MyThread extends Thread: This declares a class MyThread that extends the
Thread class. By extending Thread, MyThread can override the run() method to
define the code that will execute in the thread.
Thread Sleep:
Thread.sleep(500):
This pauses the execution of the current thread for 500
milliseconds. It simulates a time-consuming task and allows other threads to
run.
Error Handling:
Main Method:
public static void main(String[] args): The entry point of the program.
MyThread t1 = new MyThread(): A new thread instance is created.
t1.start(): This method starts the thread, which in turn calls the run() method.
PROGRAM:
try {
} catch (InterruptedException e) {
System.out.println(e);
Class Declaration:
Main Method:
public static void main(String[] args): The main method where execution starts.
MyRunnable myRunnable = new MyRunnable(): An instance of MyRunnable is created.
Thread t2 = new Thread(myRunnable): A new Thread object is created, passing the
myRunnable instance to its constructor.
t2.start(): This starts the new thread, which calls the run() method of MyRunnable.
OUTPUT:
Runnable: 1
Runnable: 2
Runnable: 3
Runnable: 4
Runnable: 5
The output consists of "Runnable: 1", "Runnable: 2", etc., printed in sequence, similar to the
first example. Again, the output order may vary.
Key Methods:
1. wait():
o Causes the current thread to wait until another thread invokes notify() or
notifyAll() on the same object.
o Must be called from a synchronized context.
2. notify():
o Wakes up a single thread that is waiting on the object's monitor.
o If multiple threads are waiting, one of them is chosen at the discretion of the thread
scheduler.
Overview:
import java.util.LinkedList;
import java.util.Queue;
class SharedBuffer {
this.capacity = capacity;
synchronized (this) {
buffer.add(value);
synchronized (this) {
while (buffer.isEmpty()) {
return value;
this.buffer = buffer;
try {
buffer.produce(i);
} catch (InterruptedException e) {
System.out.println(e);
}
class Consumer extends Thread {
this.buffer = buffer;
try {
buffer.consume();
} catch (InterruptedException e) {
System.out.println(e);
producer.start();
consumer.start();
}
}
SharedBuffer Class: Contains a Queue to hold items and methods for producing and
consuming.
o Uses synchronized blocks to ensure thread safety.
o Uses wait() and notify() to manage the buffer's state.
Producer Class: Extends Thread and produces items in a loop.
Consumer Class: Extends Thread and consumes items in a loop.
Main Class: Creates a shared buffer and starts both producer and consumer threads.
OUTPUT:
Produced: 0
Consumed: 0
Produced: 1
Produced: 2
Consumed: 1
...