被synchronized作用的对象线程,该线程sleep后,马上别的线程会接着执行。看下面程序的执行结果:
t1:0
t2:0
t2:1
t1:1
t1:2
t2:2
t2:3
t1:3
如果将 Thread.sleep(3000);注释掉,那么执行的结果变为:
t1:0
t1:1
t1:2
t1:3
t2:0
t2:1
t2:2
t2:3
public class TestThread{
public static void main(String[] args){
SynTestThreadMethod t1 = new SynTestThreadMethod("t1");
SynTestThreadMethod t2 = new SynTestThreadMethod("t2");
t1.start();
t2.start();
}
}
class SynTestThreadMethod extends Thread{
public static int shareVar = 0;
public SynTestThreadMethod(String name){
super(name);
}
public void run(){
synchronized(this) {
for(int i=0; i<4; i++){
System.out.println(Thread.currentThread().getName() +":" + i);
try{
Thread.sleep(3000);
}
catch(InterruptedException e){}
}
}
}
}