代码是书上例子,我简化了,启用线程ob1后,通过主线程调用sychonized方法mysuspend()和myresume()来控制ob1线程的等待与重启。线程从15开始倒数,0.5秒个,主线程在1秒时候暂停文字提示,再过1秒重启线程。例子中的sychonized代码块仅包含wait()判定部分,输出与预期一样,倒数到14的时候中断,之后又恢复。但是当我将sychonized代码块前移,包含至 Thread.sleep(500)之前的时候,暂停时间常常之后到13时候,当sychonized代码块前移包含整个循环语句的时候,倒数代码段根本就停不下来,结束的时候主线程才调用了下mysuspend()挂起方法,就好像整个
ob1对象被锁住似的,所以请问,sychonized代码块锁住的地方和mysuspend()挂起方法是分别加锁,双方互相独立ob1可以同时进行两个部分,为什么后两种情况明显感到ob1.mysuspend()被锁住动不了的呢?
public class NewThread implements Runnable{
String name;
Thread t;
static boolean suspendFlag;
NewThread(String threadname)
{
name=threadname;
t=new Thread(this,name);
System.out.println("New thread:"+t);
suspendFlag=false;
t.start();
}
public void run()
{
try
{
for(int i=15;i>0;i--)
{
System.out.println(name+":"+i);
Thread.sleep(500);
synchronized(this){while(suspendFlag){this.wait();}}
}
}
}catch(InterruptedException e){}
System.out.println(name+" exiting.");
}
synchronized void mysuspend(){suspendFlag=true;}
synchronized void myresume(){suspendFlag=false;notify();}
}
public static void main(String[] args) {
NewThread ob1=new NewThread("One");
NewThread ob2=new NewThread("Two");
try{
Thread.sleep(1000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(1000);
ob1.myresume();
System.out.println("Resuming thread One");
}catch(InterruptedException e){}