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


Please Help Members By Posting Answers For Below Questions

Can set contain duplicates?

538


Is class forname reflection?

511


How do you use compareto method?

524


How to read and write image from a file ?

549


What is a bubble sort in java?

537






Which is better stringbuffer or stringbuilder?

521


How do you sort objects in java?

509


define the terminology association.

607


What is the difference between the ">>" and " >>>" operators in java?

502


What does it mean that a class or member is final?

550


How to convert string to byte array and vice versa?

576


What is a java string?

533


What is the platform?

519


What are the different types of methodologies?

523


What are the characteristics of Final,Finally and Finalize keywords.

690