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
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
What is preparedstatement in java?
Tell us something about different types of casting?
What is api data?
What happens when you add a double value to a string?
What is jit compiler in java?
What one should take care of, while serializing the object?
What is a method vs function?
What is double checked locking in singleton?
What is a singleton class in Java?
Explain spliterator in java8?
Which package is always imported by default?
What is procedure overloading?
Which java version is latest?
What is use of a abstract variable?