日期:2014-05-20 浏览次数:20925 次
public class A extends Thread {
@Override
public void run() {
process();
}
private void process() {
/*......*/
}
}
public class B {
A a;
private void function() {
//......
JButton button_start = new JButton("开始");
button_start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
a = new A();
a.start();
}
});
JButton button_pause = new JButton("暂停");
button_pause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 在这里让线程a暂停
}
});
JButton button_resume = new JButton("恢复");
button_resume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 在这里让线程a继续
}
});
//......
}
}
@Deprecated
public final void suspend()
Deprecated. This method has been deprecated, as it is inherently deadlock-prone. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed. If the thread that would resume the target thread attempts to lock this monitor prior to calling resume, deadlock results. Such deadlocks typically manifest themselves as "frozen" processes. For more information, see Why are Thread.stop, Thread.suspend and Thread.resume Deprecated?.
Suspends this thread.
First, the checkAccess method of this thread is called with no arguments. This may result in throwing a SecurityException (in the current thread).
If the thread is alive, it is suspended and makes no further progress unless and until it is resumed.
Throws:
SecurityException - if the current thread cannot modify this thread.
See Also:
checkAccess()
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
class ThreadClass extends JTextField implements Runnable {
//--- flag 控制线程状态 ---
private boolean flag = true;
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
//--- 通过累计计数模拟线程运行---
int times = 0;
//--- 设置文本框主要是显示线程状态 ---
public ThreadClass(String s) {
super(s);
setBackground(Color.ORANGE);//---橘黄
setEditable(false);
setHorizontalAlignment(JTextField.CENTER);
}
@Override
public void run() {
process();
}
private synchronized void process() {
while (true) {//无限循环
if (flag == true) {
this.setText("This is the " + (times++)
+ "th times running \n");
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
notify();//--- 唤醒另一线程 --- ,本代码其实没有其他等待线程,这个可不用 ---
} else {
this.setText(" When times = " + times + "\n The thread is paused!");
try {
wait();//--- 进入等待
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
}
public class ThreadControll extends JFrame {
ThreadClass a = new ThreadClass("请按开始按钮!");
Thread startThread = null;