暫停執行緒(suspend和resume)
阿新 • • 發佈:2019-01-28
不多說程式碼演示:
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 Run { public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(3000); // A thread.suspend(); System.out.println("A= " + System.currentTimeMillis() + " i=" + thread.getI()); Thread.sleep(3000); System.out.println("A= " + System.currentTimeMillis() + " i=" + thread.getI()); // B thread.resume(); Thread.sleep(3000); // C thread.suspend(); System.out.println("B= " + System.currentTimeMillis() + " i=" + thread.getI()); Thread.sleep(3000); System.out.println("B= " + System.currentTimeMillis() + " i=" + thread.getI()); } catch (InterruptedException e) { e.printStackTrace(); } } }
suspend和resume方法缺點--獨佔
public class SynchronizedObject { synchronized public void printString() { System.out.println("begin"); if (Thread.currentThread().getName().equals("a")) { System.out.println("a執行緒永遠 suspend了!"); Thread.currentThread().suspend(); } System.out.println("end"); } } public class Run { public static void main(String[] args) { try { final SynchronizedObject object = new SynchronizedObject(); Thread thread1 = new Thread() { @Override public void run() { object.printString(); } }; thread1.setName("a"); thread1.start(); Thread.sleep(1000); Thread thread2 = new Thread() { @Override public void run() { System.out .println("thread2啟動了,但進入不了printString()方法!只打印1個begin"); System.out .println("因為printString()方法被a執行緒鎖定並且永遠的suspend暫停了!"); object.printString(); } }; thread2.start(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
public class MyThread extends Thread { private long i = 0; @Override public void run() { while (true) { i++; System.out.println(i); } } } public static void main(String[] args) { try { MyThread thread = new MyThread(); thread.start(); Thread.sleep(1000); thread.suspend(); System.out.println("main end!"); } catch (InterruptedException e) { e.printStackTrace(); } }
suspend和resume方法缺點--不同步資料
public class MyObject {
private String username = "1";
private String password = "11";
public void setValue(String u, String p) {
this.username = u;
if (Thread.currentThread().getName().equals("a")) {
System.out.println("停止a執行緒!");
Thread.currentThread().suspend();
}
this.password = p;
}
public void printUsernamePassword() {
System.out.println(username + " " + password);
}
}
public static void main(String[] args) throws InterruptedException {
final MyObject myobject = new MyObject();
Thread thread1 = new Thread() {
public void run() {
myobject.setValue("a", "aa");
};
};
thread1.setName("a");
thread1.start();
Thread.sleep(500);
Thread thread2 = new Thread() {
public void run() {
myobject.printUsernamePassword();
};
};
thread2.start();
}