Question: public class NonSynchronized { public static void main(String args[]) { MsgSender sender = new MsgSender(); Caller c1,c2,c3; c1 = new Caller(Hello, sender); c2 = new

public class NonSynchronized {

public static void main(String args[]) { MsgSender sender = new MsgSender(); Caller c1,c2,c3; c1 = new Caller("Hello", sender); c2 = new Caller("World", sender); c3 = new Caller("Syncronized", sender); Thread t1 = new Thread(c1); Thread t2 = new Thread(c2); Thread t3 = new Thread(c3); t1.start(); t2.start(); t3.start();

try { t1.join(); t2.join(); t3.join(); } catch(InterruptedException ie) { }

} } class MsgSender{ void sendMsg(String msg) { System.out.print(" [ " + msg ); System.out.print(" ] "); } }

class Caller implements Runnable{ String msg; MsgSender sender; public Caller(String msg ,MsgSender sender) { this.msg = msg; this.sender = sender; } public void run() { sender.sendMsg(msg); } }

In the following attached file , if you run the code you will find an output similar to this

[ Syncronized [ World ] [ Hello ] ] or [ World [ Hello ] [ Syncronized ] ]

Please use synchronization to make the output looks like this:

[ Hello ] [ Syncronized ] [ World ]

or

[ Hello ] [ World ] [ Syncronized ]

where [ should be before the word and ] should be after the word.

No matter the order of the words is.

you can use either, Lock..Semaphore, Or Syncronized block or methods

** help me with this please

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

To ensure that the messages are printed in a synchronized manner we can use the synchronized block in the sendMsg method This will ensure that only on... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!