How to make a method thread safe without using synchronized
keyword?

Answer Posted / praveen t chand

hi

this is the correct answer for this question



public class A implements Runnable {

/**
* @author jeetendra.arora
* @param args
*/

A(){

System.out.println("Constructor..");
}
public static void main(String[] args) {

A a = new A();


Thread t1 = new Thread(a,"a thead");
t1.start();

Thread t2 = new Thread(a,"b thead");
t2.start();


}
private boolean inUse = false;
private boolean f= false;
public void run(){
System.out.println("Thread
started.."+Thread.currentThread().getName());

while(!f)
if(!inUse){
methodA();
f= true;
}
}


public void methodA(){

inUse = true;

System.out.println("processing...."+Thread.currentThread().getName());

try{
Thread.currentThread().sleep(3000);
}
catch (Exception e){
System.out.println("Exp");
}



System.out.println("complete.."+Thread.currentThread().getName());
inUse = false;

}

}

regards
praveen

Is This Answer Correct ?    0 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

can java object be locked down for exclusive use by a given thread? Or what happens when a thread cannot acquire a lock on an object? : Java thread

528


What is preparedstatement in java?

553


Tell us something about different types of casting?

513


What is api data?

526


What happens when you add a double value to a string?

534






What is jit compiler in java?

575


What one should take care of, while serializing the object?

480


What is a method vs function?

545


What is double checked locking in singleton?

602


What is a singleton class in Java?

501


Explain spliterator in java8?

593


Which package is always imported by default?

539


What is procedure overloading?

1796


Which java version is latest?

531


What is use of a abstract variable?

533