How to make a method thread safe without using synchronized
keyword?
Answer Posted / jitender arora
Corrected my previous answer:
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);
t1.start();
Thread t2 = new Thread(a);
t2.start();
}
public void run(){
System.out.println("Thread
started.."+Thread.currentThread().getName());
Thread.currentThread().getName();
methodA();
}
private boolean inUse = false;
public void methodA(){
while(!inUse){
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;
}
}
| Is This Answer Correct ? | 5 Yes | 9 No |
Post New Answer View All Answers
What is a generic type?
How does callback work in java?
How do you square a number?
What is a local, member and a class variable?
What is difference between array and arraylist in java?
I want my class to be developed in such a way that no other class (even derived class) can create its objects. Define how can I do so?
What is the difference between path and classpath variables?
What is serialversionuid?
Can we create an object of private class?
What do you mean by thread safe?
Define class?
What is string syntax?
What purpose do the keywords final, finally, and finalize fulfill?
Can a class extend 2 classes in java?
What is the function of character?