Synchronized Statement Assignment Help

Assignment Help: >> Synchronization - Synchronized Statement

Synchronized Statement:

Although creating synchronized methods inside classes which you create is an simple an effective means of achieving  synchronization, it will not work in all cases. For understand why, let consider the following. Imagine which you need to synchronize access to objects of a class which was not designed for multithreaded access. That is, the class does not use synchronized methods. Additionally, this class was not created through you but through a third party and you do not have access to the source code.  Therefore, you can't add synchronized to the suitable methods inside the class. How can access to an object of this class be synchronized? Fortunately, the solution to this program is quite simple. You have to simply put calls to the methods defined through this class within a synchronized block.

This is the common form of the synchronized statement.

synchronized (object) {

/ / statements to be synchronized

}

Here object is a reference to the object being synchronized the curly braces are not needed if you want to synchronize only a single statement. A synchronized block ensures in which a call to a method which is a member of object occurs only after the current thread has successfully entered object's monitor.

Here is an instead version of the preceding instance, by using a synchronized block inside the run( ) method.

// This program uses a synchronized block.

Class Callme{

void call (string msg){

System.out.print("["+msg);

try{ Thread.sleep(1000);

}catch (InterruptedException e){

System.out.println("Interrupted");

system.out.println("]");

}

}

class Caller implements Runnable{

String msg;

Callme target; Thread t;

Public Caller(Callme targ , String s)

Target = targ;

msg = s;

t = new Thread (this);

t.start();          

}

//synchronize calls to call()

public void run(){

synchronized(target){

//synchronized block

target.call(msg);

}

}

}

class Synch1{

public static void main(String args[]){

Callme target = new Callme();

Caller ob1 = new Caller(target,"hello");

Caller ob2 = new Caller (target, "Synchronized");

Caller ob3 = new Caller (targer,"World");

//wait for threads to end try{

ob1.t.join();

ob2.t.join();

ob3.t.join();

}

catch(InterruptedException e){

System .out.println("Interrupted");

}

}

}

Here, the call () function is not changed through synchronized. Alternatively, the synchronized statement is used within Caller's run() method. This causes the similar correct output as the preceding instance, since each thread waits for the prior one to complete before proceeding.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd