Synchronized run

Suppose we have:

publicclass Synco1extends Thread{

staticint i=0;

Object o;

int j=0;

public Synco1(Object o){

this.o=o;

}

public syncronizedvoid run(){

while (j<5){

//synchronized (o){

System.out.print(Thread.currentThread()+"i before increase "+ i);

try{

Thread.sleep(1000);

}catch(InterruptedException e){System.out.print("Exception");};

j++;

i++;

System.out.println(" ");

System.out.print(Thread.currentThread()+"i afther increase"+ i);

System.out.println(" ");

//}

}

}

}

publicclass Synco1Tester{

/**

* @param args

*/

publicstaticvoid StartThread(Thread t){

t.start();

}

publicstaticvoid main(String[] args){

// TODO Auto-generated method stub

Integer p=new Integer(1);

Synco1 t1=new Synco1(p);

t1.setName("Thread1");

Synco1 t2=new Synco1(p);

t2.setName("Thread2");

StartThread(t1);

StartThread(t2);

}

}

I know the correct way to synchronize is like // syncronize (o) , but whypublic syncronize run (); doesn't synchronize the method run? (excuse the mess word)

[2777 byte] By [puntinoa] at [2007-11-27 0:50:57]
# 1

By synchronizing the run method, you prevent this method to be called concurrently on a given instance of Synco1 (synchronized instance methods use this as the lock).

In other words:synchronized void method() {

// code

}

is equivalent to void method() {

synchronized(this) {

// code

}

}

TimTheEnchantora at 2007-7-11 23:21:31 > top of Java-index,Java Essentials,Java Programming...
# 2
excuse me, TimTheEnchantor, you say:you prevent this method to be called concurrently on a given instance of Synco1I don' understand. Why can i use the syncronized on the refence this and not on the method run?
puntinoa at 2007-7-11 23:21:31 > top of Java-index,Java Essentials,Java Programming...
# 3
Because you always use an object as a synchronization lock, not a method. That's how Java works. Read the tutorial: http://java.sun.com/docs/books/tutorial/essential/concurrency/
DrClapa at 2007-7-11 23:21:31 > top of Java-index,Java Essentials,Java Programming...