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 class and its types?
What will happen if static modifier is removed from the signature of the main method?
What do you mean by collectors in java 8?
How many threads can java run?
What if the main() method is declared as private? What happens when the static modifier is removed from the signature of the main() method?
How can you read content from file in java?
How java uses the string and stringbuffer classes?
What does singleton class mean?
Why java applets are more useful for intranets as compared to internet?
Why java is secure? Explain.
what are the methods in object?
What is the difference between private & public & friendly classes?
what state does a thread enter when it terminates its processing? : Java thread
Can we overload the constructors?
How do you declare an empty string?