一 . 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