Practical: 10 Write A Program For Thread Synchronization. Algorithm
Practical: 10 Write A Program For Thread Synchronization. Algorithm
Algorithm:
Step 1: Start.
Step 2: Create a class name MyThread which inherits the class Thread.
Step 3: Declare and define an array message of type string and declare it static.
Step 4: Create a constructor of the class MyThread to set the value of the id.
Step 5: Create the void run() method to display the name of the thread and the message.
Step 6: Create randomWait() method and call sleep method in that method to make thread
wait for a particular interval of time.
Step 7: Create another class named SynchronizedOutput and in this class create a static
synchronized displayList() method which takes two string arguments name and list.
Step 8: In the displayList() method call the currentThread() and the randomWait() method and
print the values of name and the list.
Step 9: Create another class named ThreadSynchronization in which main method is created.
Step 10: In main method create the objects of the MyThread class and call the start() methid by
the objects of the class MyThread.
Step 11: Declare two variables thread1isAlive and thread2isAlive of type Boolean and initialize
them as true.
Step 12: Check if thread1 or thread2 is alive or dead and print the same.
super(id);
SynchronizedOutput.displayList(getName(),message);
void randomWait()
try
sleep((long)(3000*Math.random()));
catch (InterruptedException x)
System.out.println("Interrupted!");
}
class SynchronizedOutput
for(int i=0;i<list.length;++i) {
MyThread t = (MyThread)Thread.currentThread();
t.randomWait();
System.out.println(name+list[i]);
class ThreadSynchronization
thread1.start();
thread2.start();
do {
thread1IsAlive = false;
System.out.println("Thread 1 is dead.");
thread2IsAlive = false;
System.out.println("Thread 2 is dead.");
} while(thread1IsAlive || thread2IsAlive);
}
OUTPUT: