|
| 1 | + |
| 2 | +// A Java program to demonstrate working of |
| 3 | +// synchronized. |
| 4 | +import java.io.*; |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +// A Class used to send a message |
| 8 | +class Sender { |
| 9 | + public void send(String msg) { |
| 10 | + System.out.println("Sending\t" + msg); |
| 11 | + try { |
| 12 | + Thread.sleep(1000); |
| 13 | + } catch (Exception e) { |
| 14 | + System.out.println("Thread interrupted."); |
| 15 | + } |
| 16 | + System.out.println("\n" + msg + "Sent"); |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +// Class for send a message using Threads |
| 21 | +class ThreadedSend extends Thread { |
| 22 | + private String msg; |
| 23 | + Sender sender; |
| 24 | + |
| 25 | + // Recieves a message object and a string |
| 26 | + // message to be sent |
| 27 | + ThreadedSend(String m, Sender obj) { |
| 28 | + msg = m; |
| 29 | + sender = obj; |
| 30 | + } |
| 31 | + |
| 32 | + public void run() { |
| 33 | + // Only one thread can send a message |
| 34 | + // at a time. |
| 35 | + synchronized (sender) { |
| 36 | + // synchronizing the snd object |
| 37 | + sender.send(msg); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +// Driver class |
| 43 | +class synchronization { |
| 44 | + public static void main(String args[]) { |
| 45 | + Sender snd = new Sender(); |
| 46 | + ThreadedSend S1 = new ThreadedSend(" Hi ", snd); |
| 47 | + ThreadedSend S2 = new ThreadedSend(" Bye ", snd); |
| 48 | + |
| 49 | + // Start two threads of ThreadedSend type |
| 50 | + S1.start(); |
| 51 | + S2.start(); |
| 52 | + |
| 53 | + // wait for threads to end |
| 54 | + try { |
| 55 | + S1.join(); |
| 56 | + S2.join(); |
| 57 | + } catch (Exception e) { |
| 58 | + System.out.println("Interrupted"); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments