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
Does java have a compiler?
When we serialize an object does the serialization mechanism saves its references too?
What are advantages of exception handling in java?
Do you know why doesn't the java library use a randomized version of quicksort?
What is * argv?
Objects or references which of them gets garbage collected?
How strings are created in java?
why an outer class cannot be declared as private?
Can we define a package statement after the import statement in java?
What is get () in java?
What is an object’s lock and which object’s have locks?
Can a set contain duplicates?
What is an image buffer?
How does multithreading take place on a computer with a single cpu?
What is the intersection and union methods?