I am trying to run a simple multi-threaded program in java that uses a synchronized block inside a non-static method.I have a class TestThread which has a field string which is a StringBuffer variable. I have created two threads one and two and each of their string variables initialized to StringBuffer b which contains the value A . The first thread that goes to running state has to display the value A hundred times and after that increment it by one so that the next thread running will display the incremented value B hundred times too.I have used the current object denoted by this inside the synchronized. But unfortunately I am not getting the expected output. The first thread is displaying A more than hundred times and second thread is displaying B less than 100. And each time I run it, I am getting different outputs.So I think that the mutual exclusion is not achieved. What I am doing wrong here?
public class TestThread extends Thread{ StringBuffer string; public void run(){ synchronized(this){ for(int i=0;i<100;i++){ System.out.print(this); } System.out.println(); string.setCharAt(0,(char)(string.charAt(0)+1)); } } public TestThread(StringBuffer string){ this.string=string; } public String toString(){ return string.toString(); } public static void main(String args[]){ StringBuffer b=new StringBuffer("A"); TestThread one=new TestThread(b); TestThread two=new TestThread(b); one.start(); two.start(); } }
new Threadsynchronizedthe choice of object to lock on matters, you need to lock on the same object as the other thread, the obvious choice being the object you want to modify e.g. theStringthisis different for different threads. Got it?