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 difference between preemptive scheduling and time slicing?
How do you declare a destructor in java?
Howto get an object that will perform date & time calculations then format it for output in some different locales with different date style.can ne1 tel me the answer of this question.pls
Can an interface have a constructor?
What is the public method modifier?
What is style and indentation?
What are the legal parameters?
why Java does not support multiple inheritances?
Java is Pass by Value or Pass by Reference?
How does map works in java?
What is boolean example?
What is a bubble sort in java?
Does string is thread-safe in java?
Can a class be private in java?
What is substring 1 in java?