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
Can set contain duplicates?
Is class forname reflection?
How do you use compareto method?
How to read and write image from a file ?
What is a bubble sort in java?
Which is better stringbuffer or stringbuilder?
How do you sort objects in java?
define the terminology association.
What is the difference between the ">>" and " >>>" operators in java?
What does it mean that a class or member is final?
How to convert string to byte array and vice versa?
What is a java string?
What is the platform?
What are the different types of methodologies?
What are the characteristics of Final,Finally and Finalize keywords.