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
How to read and write image from a file ?
What is the best way to findout the time/memory consuming process?
What is the public field modifier?
Is map ordered in java?
What is java argument list?
If an application has multiple classes in it, is it okay to have a main method in more than one class?
How many bytes is string in java?
What is hashset in java?
How do generics work?
What is the difference between delete and delete[]
Differentiate jar and war files?
What is one third plus one third as a fraction?
What does system out println () do?
What is stringjoiner ?
What is static keyword in java?