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 do you add an element to a set in java?
Can we override constructors?
How many types of constructors are used in java?
What are the types of methods in java?
Can you declare an interface method static?
What is the purpose of the wait(), notify(), and notifyall() methods in java programming?
What are heterogeneous objects?
Can an interface implement another interface?
Does string is thread-safe in java?
What is the advantage of OOP in java?
How many types of literals are there in JAVA?
What is ascii code?
What is broken and continue statement?
What is function and its uses?
Can you explain the usages of class.forname()?