Hi,
Threads commonly share the same memory space area, that’s why they can share the resources. Threads commonly communicate by sharing access to fields and the objects reference fields refer to. This communication type is extremely efficient, but makes two kinds of problems: thread interference and memory consistency errors. By the synchronization tool we can avoid this problem.
Synchronized methods are useful in those situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. Stack implementations usually define the two operations push and pop of elements as synchronized, that’s why pushing and popping are mutually exclusive operations. For Example if several threads were sharing a stack, if one thread is popping the element on the stack then another thread would not be able to pushing the element on the stack.
The following program demonstrates the synchronized method:
public class SynThread{
public static void main(String args[]){
Share s=new Share();
MyThread m1=new MyThread(s,"Thread1");
MyThread m2=new MyThread(s,"Thread2");
MyThread m3=new MyThread(s,"Thread3");
}
}
class MyThread extends Thread{
Share s;
MyThread(Share s,String str){
super(str);
this.s=s;
start();
}
public void run(){
s.doword(Thread.currentThread().getName());
}
}
class Share{
public synchronized void doword(String str){
for(int i=0;i<5;i++){
System.out.println("Started :"+str);
try{
Thread.sleep(100);
}catch(Exception e){}
}
}
}Thanks
Fuad
Offline