-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleChat.java
More file actions
84 lines (69 loc) · 2.34 KB
/
Copy pathSimpleChat.java
File metadata and controls
84 lines (69 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
public class SimpleChat {
public static void main(String[] args) throws InterruptedException {
// Create two chat users with messages
ChatUser user1 = new ChatUser("Soham", new String[]{"Hi", "How are you?", "Bye!"});
ChatUser user2 = new ChatUser("Shivam", new String[]{"Hello Soham", "I am fine!", "OK See you soon Bye!"});
// Start both chat threads
user1.start();
user2.start();
System.out.println("Soham alive? " + user1.isAlive());
Thread.sleep(1000);
// Pause Shivam
user2.pauseChat();
System.out.println("Shivam paused...");
Thread.sleep(1000);
// Resume Shivam
user2.resumeChat();
System.out.println("Shivam resumed...");
Thread.sleep(1000);
// Stop Soham
user1.stopChat();
System.out.println("Soham stopped...");
// Wait for both threads to finish
user1.join();
user2.join();
System.out.println("Soham alive after join? " + user1.isAlive());
System.out.println("Chat ended.");
}
}
class ChatUser extends Thread {
private String[] messages;
private volatile boolean running = true;
private volatile boolean paused = false;
ChatUser(String name, String[] messages) {
super(name);
this.messages = messages;
}
// Pause the chat
public void pauseChat() {
paused = true;
}
// Resume the chat
public synchronized void resumeChat() {
paused = false;
notify();
}
// Stop the chat
public void stopChat() {
running = false;
}
public void run() {
for (int i = 0; i < messages.length && running; i++) {
synchronized (this) {
while (paused) {
try {
wait(); // wait until resumeChat() is called
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(getName() + " says: " + messages[i]);
try {
Thread.sleep(1000); // delay between messages
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}