暫停線(xiàn)程意味著此線(xiàn)程還可以恢復(fù)運(yùn)行届榄。在java多線(xiàn)程中,還可以使用suspend()方法暫停線(xiàn)程倔喂,使用resume()方法恢復(fù)線(xiàn)程的執(zhí)行铝条。
/**
* MyThread線(xiàn)程測(cè)試
* @author wuyoushan
* @date 2017/3/21.
*/
public class MyThread extends Thread {
private long i=0;
public Long getI() {
return i;
}
public void setI(long i) {
this.i = i;
}
@Override
public void run() {
while (true){
i++;
}
}
}
/**
* @author wuyoushan
* @date 2017/3/20.
*/
public class Run {
public static void main(String[] args){
try{
MyThread thread=new MyThread();
thread.start();
Thread.sleep(5000);
//A段
thread.suspend();
System.out.println("A="+System.currentTimeMillis()+"i="+thread.getI());
Thread.sleep(5000);
System.out.println("A="+System.currentTimeMillis()+"i="+thread.getI());
//B段
thread.resume();
Thread.sleep(5000);
//C段
thread.suspend();
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();
}
}
}
從控制臺(tái)的打印結(jié)果來(lái)看,線(xiàn)程的確被暫停了席噩,而且還可以恢復(fù)成運(yùn)行狀態(tài)班缰。
A=1490576230229i=2056518687
A=1490576235229i=2056518687
B=1490576240229i=4141381898
B=1490576245229i=4141381898
摘選自 java多線(xiàn)程核心編程技術(shù)-1.8