直接上代码:
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(1000);
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 class SuspendResume {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
NewThread ob1=new NewThread("One");
try{
Thread.sleep(2000);
ob1.mysuspend();
System.out.println("Suspending thread One");
Thread.sleep(2000);
ob1.myresume();
System.out.println("Resuming thread One");
Thread.sleep(2000);
}catch(InterruptedException e){}
try{System.out.println("Waiting for threads to finiish.");
ob1.t.join();
}catch(InterruptedException e){}
System.out.println("Main thread exiting.");
}
}
运行结果:
New thread:Thread[One,5,main]
One:15
One:14
One:13
Suspending thread One
One:12
Resuming thread One
One:11
One:10
Waiting for threads to finiish.
One:9
One:8
One:7
One:6
One:5
One:4
One:3
One:2
One:1
One exiting.
Main thread exiting.
如预期一样,ob1.mysuspend();ob1.myresume();的调用在ob1线程运行中是正常时间控制挂起和重启。
但将run()方法中synchronized(this){}模块稍微修改:
public void run()
{
try
{
synchronized(this){
for(int i=15;i>0;i--)
{
System.out.println(name+":"+i);
Thread.sleep(1000);
while(suspendFlag){this.wait();}
}
}
}catch(InterruptedException e){}
System.out.println(name+" exiting.");
}
其余代码不变
结果是:
New thread:Thread[One,5,main]
One:15
One:14
One:13
One:12
One:11
One:10
One:9
One:8
One:7
One:6
One:5
One:4
One:3
One:2
One:1
Suspending thread One
One exiting.
Resuming thread One
Waiting for threads to finiish.
Main thread exiting.
结果是主线程对ob1.mysuspend();ob1.myresume();的调用没有按照预期的时间进行,而是卡在ob1线程运行结束后才开始调用,就好像ob1得运行将ob1.mysuspend();ob1.myresume();锁住一样,sychonized模块将循环体包围住,mysuspend()就像被锁住不能动了似的,为什么会有两次的运行结果差异?谢谢。