由於線程可能進入堵塞狀態
就語言本身來說
為減少出現死鎖的可能
之所以反對使用stop()
如果一個線程被堵塞
//: Interrupt
// The alternative approach to using stop()
// when a thread is blocked
import java
import java
import java
class Blocked extends Thread {
public synchronized void run() {
try {
wait(); // Blocks
} catch(InterruptedException e) {
System
}
System
}
}
public class Interrupt extends Applet {
private Button
interrupt = new Button(
private Blocked blocked = new Blocked();
public void init() {
add(interrupt);
interrupt
new ActionListener() {
public
void actionPerformed(ActionEvent e) {
System
if(blocked == null) return;
Thread remove = blocked;
blocked = null; // to release it
remove
}
});
blocked
}
public static void main(String[] args) {
Interrupt applet = new Interrupt();
Frame aFrame = new Frame(
aFrame
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System
}
});
aFrame
aFrame
applet
applet
aFrame
}
} ///:~
Blocked
suspend()和resume()方法天生容易發生死鎖
//: Suspend
// The alternative approach to using suspend()
// and resume()
// in Java
import java
import java
import java
public class Suspend extends Applet {
private TextField t = new TextField(
private Button
suspend = new Button(
resume = new Button(
class Suspendable extends Thread {
private int count =
private boolean suspended = false;
public Suspendable() { start(); }
public void fauxSuspend() {
suspended = true;
}
public synchronized void fauxResume() {
suspended = false;
notify();
}
public void run() {
while (true) {
try {
sleep(
synchronized(this) {
while(suspended)
wait();
}
} catch (InterruptedException e){}
t
}
}
}
private Suspendable ss = new Suspendable();
public void init() {
add(t);
suspend
new ActionListener() {
public
void actionPerformed(ActionEvent e) {
ss
}
});
add(suspend);
resume
new ActionListener() {
public
void actionPerformed(ActionEvent e) {
ss
}
});
add(resume);
}
public static void main(String[] args) {
Suspend applet = new Suspend();
Frame aFrame = new Frame(
aFrame
new WindowAdapter() {
public void windowClosing(WindowEvent e){
System
}
});
aFrame
aFrame
applet
applet
aFrame
}
}
Suspendable中的suspended(已掛起)標志用於開關
Thread的destroy()方法根本沒有實現
大家可能會奇怪當初為什麼要實現這些現在又被
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19400.html