Thread suspend()挂起resume()恢复

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ThreadVSR extends JPanel implements Runnable{
private static final String[] symbolList={"|","/","--","\\","/","--","\\"};
private Thread runThread;
private JTextField symbolTF;

public ThreadVSR() {
symbolTF=new JTextField();
symbolTF.setEditable(false);
symbolTF.setFont(new Font("Monospaced",Font.BOLD,26));
symbolTF.setHorizontalAlignment(JTextField.CENTER);
final JButton suspendB=new JButton("suspend");
final JButton resumeB=new JButton("resume");
suspendB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
suspendNow();
}
});
resumeB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resumeNow();
}
});
JPanel in=new JPanel();
in.setLayout(new GridLayout(0,1,3,3));
in.add(symbolTF);
in.add(suspendB);
in.add(resumeB);
this.setLayout(new FlowLayout(FlowLayout.CENTER));
this.add(in);
}
private void suspendNow(){
if (this.runThread!=null){
runThread.suspend();
}
}
private void resumeNow(){
if (this.runThread!=null){
this.runThread.resume();
}
}

@Override
public void run() {
try {
runThread=Thread.currentThread();
int count=0;
while (true){
symbolTF.setText(symbolList[count%symbolList.length]);
Thread.sleep(200);
count++;
System.out.println(count);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
runThread=null;
}
public static void main(String[] args){
ThreadVSR vrs=new ThreadVSR();
Thread t=new Thread(vrs);
t.start();
JFrame f=new JFrame("suspend-resume-");
f.setContentPane(vrs);
f.setSize(320,200);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
posted @ 2017-09-19 20:44  蓬鹏  阅读(975)  评论(0编辑  收藏  举报