【发布时间】:2014-07-08 01:28:29
【问题描述】:
在我用 java 编写的项目中手动停止线程后,我试图重新启动它。当我尝试重新启动它时,我收到了 IllegalThreadStateException 错误。
我将我的代码简化为以下示例代码。我的问题是:
如何重新启动 logtest 线程,是否必须启动一个新线程而不是重新启动它?
从下面的代码可以看出,在LogThread类的run方法中,我使用Thread.Sleep(3)来逐行输出这些数字。如果我删除这一行,线程要么死在中间,要么一次性输出所有这 10000 行。我是否必须强制线程停止 3 毫秒以牺牲其性能?有没有更好的方法来解决这个问题?
代码:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.StyledDocument;
public class LogTest {
private LogThread logtest;
public LogTest() {
JFrame frame = new JFrame("LogTest");
Container con = frame.getContentPane();
final JTextPane pane = new JTextPane();
final JScrollPane scollPane = new JScrollPane(pane);
JButton button = new JButton("Start Test Log");
JButton button1 = new JButton("Stop Test Log");
logtest = new LogThread(pane);
con.add(scollPane);
con.add(button, BorderLayout.NORTH);
con.add(button1, BorderLayout.SOUTH);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
logtest.start();
}
});
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
logtest.stop();
}
});
frame.setSize(600, 500);
frame.setVisible(true);
}
public static void main(String[] args) {
new LogTest();
}
}
class LogThread implements Runnable {
private final Thread t;
private String newline;
private volatile boolean shouldStop = false;
private StyledDocument doc;
private JTextPane pane;
private static int counter = 0;
public LogThread(JTextPane pane) {
this.doc = pane.getStyledDocument();
this.pane = pane;
t = new Thread(this, "Log Thread");
newline = System.getProperty("line.separator");
}
public void start() {
t.start();
}
public void run() {
try {
if (doc.getLength() > 0) {
doc.remove(0, doc.getLength());
}
} catch (Exception e) {
e.printStackTrace();
}
if(shouldStop) shouldStop=false;
for (int i = counter; i <= 1000 && !shouldStop; i++) {
try {
doc.insertString(doc.getLength(),
i + "-------------------------------------------------------------"+ newline,
null);
pane.setCaretPosition(doc.getLength());
Thread.sleep(3);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void stop() {
shouldStop = true;
}
}
【问题讨论】:
-
你不能。
Thread是不可重入的,这意味着您不能多次调用start。您需要创建一个新的Thread并将其传递给Runnable实例的引用并启动Thread
标签: java multithreading restart