Java 中可以使用suspend()方法来暂停线程运行,通过resume()方法来恢复线程执行
public class MyThread extends Thread {
private long i;
public long getI() {
return i;
}
public void setI(long i) {
this.i = i;
}
@Override
public void run() {
while (true) {
i++;
}
}
}
public class Run {
public static void main(String[] args) {
try {
MyThread thread = new MyThread();
thread.start();
Thread.sleep(2000);
//A段
thread.suspend();
System.out.println("A="+System.currentTimeMillis()+",i="+thread.getI());
Thread.sleep(2000);
System.out.println("A="+System.currentTimeMillis()+",i="+thread.getI());
//B段
thread.resume();
Thread.sleep(2000);
System.out.println("B="+System.currentTimeMillis()+",i="+thread.getI());
Thread.sleep(2000);
//C段
thread.suspend();
System.out.println("C="+System.currentTimeMillis()+",i="+thread.getI());
Thread.sleep(2000);
System.out.println("C="+System.currentTimeMillis()+",i="+thread.getI());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
显然,方法suspend和resume都是已经被废弃的方法
suspend()和resume()缺点
容易造成公共同步对象的独占
对于添加了同步锁的对象,如果在该方法中调用了suspend()方法,将导致对象锁无法释放,其他线程无法访问的问题。
网友评论