-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram8.java
57 lines (48 loc) · 1.83 KB
/
program8.java
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
class MessagePrinter {
// Synchronized method to print the message with square braces
synchronized void printMessage(String message) {
System.out.print("[" + message + "]");
}
}
class ChildThread extends Thread {
private MessagePrinter messagePrinter;
private String message;
public ChildThread(MessagePrinter messagePrinter, String message) {
this.messagePrinter = messagePrinter;
this.message = message;
}
public void run() {
// Calling the synchronized method
messagePrinter.printMessage(message);
}
}
public class program8 {
public static void main(String[] args) throws InterruptedException {
// Create an instance of MessagePrinter
MessagePrinter messagePrinter = new MessagePrinter();
// Create three child threads with different messages
ChildThread thread1 = new ChildThread(messagePrinter, "Learn");
ChildThread thread2 = new ChildThread(messagePrinter, "Java");
ChildThread thread3 = new ChildThread(messagePrinter, "Programming");
// Without synchronization (may produce interleaved output)
System.out.println("Output without synchronization:");
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
System.out.println(); // To separate outputs
// With synchronization (produces synchronized output)
System.out.println("Output with synchronization:");
thread1 = new ChildThread(messagePrinter, "Learn");
thread2 = new ChildThread(messagePrinter, "Java");
thread3 = new ChildThread(messagePrinter, "Programming");
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
}
}