I am learning synchronized blocks with locks.I want to know the difference between this lock and some third party lock that provided in the program.
public class NewThread extends Thread { StringBuffer sb; NewThread(StringBuffer sb){ this.sb=sb; } public void run(){ synchronized(this.sb){ for(int i=0;i<1000;i++){ System.out.print(sb); try{ Thread.sleep(5*60); } catch(Exception e){} } char c = this.sb.charAt(0); this.sb.setCharAt(0, ++c); } } public static void main(String[] args){ StringBuffer sb=new StringBuffer("A"); NewThread nt=new NewThread(sb); NewThread nt1=new NewThread(sb); NewThread nt2=new NewThread(sb); nt.start(); nt1.start(); nt2.start(); } }
If i am going to put
public void run(){ synchronized(this){ for(int i=0;i<1000;i++){ System.out.print(sb); try{ Thread.sleep(5*60); } catch(Exception e){} } char c = this.sb.charAt(0); this.sb.setCharAt(0, ++c); } } here in the above run method i gave this in the synchronized block ...i want the difference between them
i am having one more question ,if we are giving a lock object in synchronized block and we are not using that object inside that block then does we observe any thing specific compared to normal block