暂停线程即线程还可以恢复运行。Java多线程中,可以使用suspend()方法暂停线程,使用resume()方法恢复线程执行。
一、基本使用
public class MyThread extends Thread{
private long i = 0;
public long getI()
{
return i;
}
public void setI(long i)
{
this.i = i;
}
public void run()
{
while(true)
{
i++;
}
}
}public class App {
public static void main(String[] args)
{
try
{
MyThread thread = new MyThread();
thread.start();
Thread.sleep(500);
thread.suspend();
System.out.println("A= "+System.currentTimeMillis()+" i="+thread.getI());
Thread.sleep(5000);
System.out.println("A= "+System.currentTimeMillis()+" i="+thread.getI());
thread.resume();
System.out.println("B= "+System.currentTimeMillis()+" i="+thread.getI());
Thread.sleep(5000);
System.out.println("B= "+System.currentTimeMillis()+" i="+thread.getI());
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
Output:
A= 1500717071978 i=93100885
A= 1500717076979 i=93100885
B= 1500717076979 i=93127095
B= 1500717081980 i=1091104232
二、suspend与resume缺点
1、独占
在使用suspend与resume方法时,如果使用不当,极易造成公共的同步对象独占,是的其它线程无法访问公共同步对象。
-