一 . suspend()与resume()方法的使用
创建MyThread类
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++; } } }
创建调用类:
public class Test { public static void main(String[] args) { try { MyThread myThread = new MyThread(); myThread.start(); Thread.sleep(2000); myThread.suspend(); System.out.println(" the value of i = " + myThread.getI() + "and the time is : " + System.currentTimeMillis()); Thread.sleep(5000); System.out.println(" the value of i = " + myThread.getI() + "and the time is : " + System.currentTimeMillis()); myThread.resume(); Thread.sleep(5000); myThread.suspend(); System.out.println(" the value of i = " + myThread.getI() + "and the time is : " + System.currentTimeMillis()); Thread.sleep(5000); System.out.println(" the value of i = " + myThread.getI() + "and the time is : " + System.currentTimeMillis()); } catch (Exception e) { e.printStackTrace(); } }}
运行结果:
二 . suspend()与resume()的缺点
1 . 独占
在使用suspend()与resume()方法时,如果使用不当,极易造成公共的同步对象的独占,使得其他线程无法访问公共同步对象
2 . suspend()与resume()的缺点 --- 不同步