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
What is the purpose of abstract class?
What are the restrictions imposed by a Security Manager on Applets?.
What do u mean by variable?
What is space character in java?
Why chararray() is preferred over string to store the password?
Which browsers work with java?
What's the purpose of using break in each case of switch statement?
Explain polymorphism citing an example.
What does void * mean?
What is the use of parse function in java?
What is the difference between conversation & casting?
How do you clear a list in java?
What is another word for methodology?
What is the final keyword?
What are the advantages of functions?