
Dear Friend,
I have written below program for synchronized method in java but it's not working plz help me.
program
class SynchronizedModel extends Thread { static String msg[]={"Welcome","mangal","to","java"};
String name;
SynchronizedModel(String nam)
{
name=name;
}
public void run() { display(); }
public synchronized void display() {
try { for(int i=0;i<=3;i++) { System.out.println(this.name+" : "+msg[i]);
this.sleep(1000); }
}
catch(Exception g) { g.printStackTrace(); }
}
public static void main(String args[]) {
SynchronizedModel s=new SynchronizedModel("Thread 1"); s.start();
SynchronizedModel s1=new SynchronizedModel("Thread 2"); s1.start(); } }

The synchronized is a keyword used in Java ensures that only one Java thread execute an object's synchronized method at a time. The concept lies on the thread, that allows the threads to wait for resources to become available and also notify the thread that makes resource available to notify other threads are on the queues for the resources. We have modified your code. It now displays the thread name with the message you have given twice (for thread 1 and Thread 2).
class SynchronizedModel extends Thread
{
static String msg[]={"Welcome","mangal","to","java"};
String name;
SynchronizedModel(String nam){
name=nam;
}
public void run(){
display();
}
public synchronized void display(){
try{
for(int i=0;i<msg.length;i++){
System.out.println(this.name+" : "+msg[i]);
this.sleep(1000);
}
}
catch(Exception g){
g.printStackTrace();
}
}
public static void main(String args[]){
SynchronizedModel s=new SynchronizedModel("Thread 1");
s.start();
SynchronizedModel s1=new SynchronizedModel("Thread 2");
s1.start();
}
}
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.