一 . suspend()与resume()方法的使用ide
建立MyThread类this
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()的缺点get
1 . 独占同步
在使用suspend()与resume()方法时,若是使用不当,极易形成公共的同步对象的独占,使得其余线程没法访问公共同步对象io
2 . suspend()与resume()的缺点 --- 不一样步class