嗨,我正在用java处理线程,我有下一个代码,它有一个带按钮的图形界面和一个textArea。它还使用一个线程,当我用thread1.start()运行线程时,它开始每2秒打印一个计数器(打印0,1,2,3等),接口也实现了一个actionListener,当我单击按钮时,线程必须暂停执行。但我的问题是Thread.shupend()方法已被弃用,我不知道还有哪种方法可以解决这个问题。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class thread extends Thread{
private int count;
private long seconds;
private boolean keepPrinting = true;
private JTextArea textArea;
thread(int sec,int c,JTextArea text){
count = c;
seconds = sec;
textArea = text;
}
public void run()
{
while(keepPrinting)
{
try
{
print();
sleep(seconds);
count++;
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
public void print() {
String j;
j = Integer.toString(count);
textArea.setText(j);
}
}
class Interface extends JFrame implements ActionListener{
private JTextArea text;
private JButton button;
private JPanel window;
private thread thread1;
Interface()
{
text = new JTextArea(10,10);
button = new JButton("Ejecutar");
window = new JPanel(new BorderLayout());
window.add("South",text);
window.add("North",button);
thread1 = new thread(2000,0,text);
this.add(window);
thread1.start();
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
}
}
public class MensajesHilos {
public static void main(String[] args){
Interface i = new Interface();
i.setTitle("Threads");
i.setBounds(200, 200, 300, 310);
i.setVisible(true);
}
}
- Swing不是线程安全的,所有对UI的更新都必须在事件调度线程的上下文中进行。有关更多详细信息,请参阅Swing中的并发。在您的情况下,使用
SwingWorker
可能更容易,但我们将使用它 - 通常不鼓励您直接从
Thread
扩展,而是鼓励您实现Runnable
并将其实例传递给Thread
的实例 - 您可以通过使用某种锁来控制线程的执行。使用原始的
Object#wait
和Object#notify
API或更新的并发Lock
API。为了简单起见,我使用的是旧版本。查看内部锁、同步和锁定对象以了解更多详细信息 - 需要由多个线程检查的变量应该被设为
volatile
,或者应该使用等效的Atomic
类之一。对于Atomic
类,这确保了对值的读取和写入是干净的(一次只有一个线程)。看看原子变量
例如。。。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static class Worker implements Runnable {
private int count;
private long seconds;
private JTextArea textArea;
private AtomicBoolean keepRunning = new AtomicBoolean(true);
private AtomicBoolean paused = new AtomicBoolean(false);
protected static final Object PAUSE_LOCK = new Object();
public Worker(int sec, int c, JTextArea text) {
count = c;
seconds = sec;
textArea = text;
}
public void stop() {
keepRunning.set(false);
setPaused(false);
}
public void setPaused(boolean value) {
if (paused.get() != value) {
paused.set(value);
if (!value) {
synchronized (PAUSE_LOCK) {
PAUSE_LOCK.notifyAll();
}
}
}
}
protected void checkPausedState() {
while (paused.get() && !Thread.currentThread().isInterrupted()) {
System.out.println("I be paused");
synchronized (PAUSE_LOCK) {
try {
PAUSE_LOCK.wait();
} catch (InterruptedException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public void run() {
while (keepRunning.get() && !Thread.currentThread().isInterrupted()) {
checkPausedState();
if (keepRunning.get() && !Thread.currentThread().isInterrupted()) {
try {
System.out.println(count);
print(count);
Thread.sleep(seconds);
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void print(final int j) {
if (EventQueue.isDispatchThread()) {
textArea.append(Integer.toString(j) + "n");
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
print(j);
}
});
}
}
protected boolean isPaused() {
return paused.get();
}
}
public static class UI extends JFrame implements ActionListener {
private JTextArea text;
private JButton button;
private Worker worker;
public UI() {
text = new JTextArea(10, 10);
button = new JButton("Pause/Resume");
add(text);
add(button, BorderLayout.NORTH);
worker = new Worker(2000, 0, text);
Thread t = new Thread(worker);
t.start();
button.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
worker.setPaused(!worker.isPaused());
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
UI frame = new UI();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}