suspend()挂起线程,resume()恢复线程
..不过我在看API的时候..这两个方法已经是过时的了...
我用了另外一个方法来实现挂起和恢复线程的工作...
[CODE]
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MultiThread extends JFrame implements Runnable{
private JTextField jtfShowNumber;
private JButton jbSuspend,jbResume;
private int count=0;
private volatile boolean isSuspend; //是否挂起的一个标志
public MultiThread(){
super("挂起和恢复线程");
Container container = this.getContentPane();
container.setLayout(new FlowLayout());
jtfShowNumber = new JTextField(15);
jtfShowNumber.setEditable(false);
jtfShowNumber.setHorizontalAlignment(JTextField.CENTER);
jbSuspend = new JButton("挂起");
jbSuspend.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setSuspend(); //设置挂起线程
}
});
jbResume = new JButton("恢复");
jbResume.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setResume(); //设置恢复线程
}
});
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,1,3,3));
panel.add(jtfShowNumber);
panel.add(jbSuspend);
panel.add(jbResume);
container.add(panel);
this.setSize(200,150);
Dimension dimension = this.getToolkit().getScreenSize(); //得到屏幕的大小
//设置JFrame的搁置.
this.setLocation((dimension.width-getSize().width)/2,(dimension.height-getSize().height)/2);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭时退出程序
}
public void run(){
try{
while(true){
waitThread(); //当挂起.就进行该过程的while
count++;
String temp = Integer.toString(count);
jtfShowNumber.setText(temp);
waitThread(); //当挂起.就进行该过程的while
Thread.sleep(200); //当前线程休眠200毫秒
}
}catch(InterruptedException e){
//抛出异常.忽略
}
}
private void waitThread() throws InterruptedException{
while(isSuspend){
Thread.sleep(200);
}
}
private void setSuspend(){ //挂起线程
isSuspend = true;
}
private void setResume(){ //恢复线程
isSuspend = false;
}
public static void main(String[] args){
MultiThread mthread = new MultiThread();
Thread t = new Thread(mthread);
t.start();
}
}
[/CODE]