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
How java enabled high performance?
What is the use of StringTokenizer class?
What is the difference between the size and capacity of a vector?
Is 64bit faster than 32 bit?
Why vector is used in java?
What are the differences between checked exception and unchecked exception?
Is finalize() similar to a destructor?
What is procedure overloading?
What is anagram in java?
What is a default constructor and also define copy contrucyor?
Explain the pointers in Java?
What do you understand by Header linked List?
What is enhanced loop in java?
How do you compare two objects?
Does a class inherit the constructors of its superclass in java programming?