Practical no: 05
Create a multi-threaded Java application that simulates any real time application with
required functionalities. For eg. Basic chat system in which each user (thread) sends and
receives messages. Use isAlive() to check the status of threads and join() to ensure proper
synchronization. Implement thread priorities to handle high-priority messages and
demonstrate thread suspension, resumption, and stopping
Program:
class ChatUser extends Thread {
private String userName;
private String[] messages;
private boolean paused = false;
private boolean stopped = false;
public ChatUser(String name, String[] messages) {
[Link] = name;
[Link] = messages;
}
public void pauseChat() {
paused = true;
}
public void resumeChat() {
paused = false;
synchronized (this) {
notify(); // Resume the thread if it was paused
}
}
public void stopChat() {
stopped = true;
synchronized (this) {
notify(); // Wake thread if it's paused
}
}
public void run() {
try {
for (String message : messages) {
if (stopped) {
[Link](userName + " has left the chat.");
break;
}
synchronized (this) {
while (paused) {
wait(); // Suspend the thread safely
}
}
[Link](userName + ": " + message);
[Link](1000); // Simulate delay between messages
}
} catch (InterruptedException e) {
[Link](userName + " was interrupted.");
}
}
}
public class ChatSimulation {
public static void main(String[] args) {
String[] messages1 = {"Hi!", "How are you?", "What are you doing today?"};
String[] messages2 = {"Hello!", "I'm good, thanks!", "Let's go out!"};
ChatUser user1 = new ChatUser("Alice", messages1);
ChatUser user2 = new ChatUser("Bob", messages2);
// Set priorities
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();
try {
[Link](100);
[Link]("Is Alice alive? " + [Link]());
[Link]("Is Bob alive? " + [Link]());
[Link](2000);
[Link]("\nPausing Bob's chat...");
[Link]();
[Link](3000);
[Link]("Resuming Bob's chat...\n");
[Link]();
[Link](2000);
[Link]("Stopping Alice's chat...\n");
[Link]();
// Synchronize threads
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
[Link]("\nChat ended.");
}
}
Output: