stop()不是暂停,而且已经是不赞成的方法。
将线程转为停滞状态:
1、sleep(); //进入休眠
2、suspend(); //暂停线程,除非收到resume()消息(不赞成)
3、wait(); //暂停线程,除非收到notify()或notifyAll()消息,和2有明显的不同。
4、等待某个I/O操作
5、线程试图调用另一个对象的synchronized函数,而且尚未取得该对象的机锁你应该用wait(),具体内容........(字太多,懒的打)好好看看《Thinking in Java》第14章,里面讲的很清楚了。
<------ 树欲静而风不止 ------>
将线程转为停滞状态:
1、sleep(); //进入休眠
2、suspend(); //暂停线程,除非收到resume()消息(不赞成)
3、wait(); //暂停线程,除非收到notify()或notifyAll()消息,和2有明显的不同。
4、等待某个I/O操作
5、线程试图调用另一个对象的synchronized函数,而且尚未取得该对象的机锁你应该用wait(),具体内容........(字太多,懒的打)好好看看《Thinking in Java》第14章,里面讲的很清楚了。
<------ 树欲静而风不止 ------>
import java.awt.event.*;
import java.applet.*;public class Applet1
extends Applet {
private TextField t = new TextField(10);
private Button
button_suspend = new Button("Suspend"),
button_resume = new Button("Resume");//*******************************************************************
class Suspendable
extends Thread {
private int count = 0;
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(100);
synchronized (this) {
while (suspended){
wait();
}
}
}
catch (InterruptedException e) {}
t.setText(Integer.toString(count++));
}
}
} //***************************************************************
private Suspendable ss = new Suspendable();
public void init() {
add(t);
button_suspend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ss.fauxSuspend();
}
});
add(button_suspend);
button_resume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ss.fauxResume();
}
});
add(button_resume);
} public static void main(String[] args) {
Applet1 applet = new Applet1();
Frame aFrame = new Frame("Suspend");
aFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
aFrame.add(applet, BorderLayout.CENTER);
aFrame.setSize(300, 100);
applet.init();
applet.start();
aFrame.setVisible(true);
}
}
<------ 树欲静而风不止 ------>
不过这些方法在1.4版本的jdk中已经不再建议使用了