替换Thread.suspend()方法

时间:2015-02-13 04:41:19

标签: java multithreading

您好我正在使用java中的线程,我有下一个代码,它有一个带按钮的图形界面和一个textArea。它也使用一个线程,当我用thread1.start()运行线程时,它每2秒开始打印一个计数器(打印0,1,2,3等等),接口实现一个actionListener,当我点击线程必须暂停执行的按钮。但我的问题是Thread.suspend()方法已被弃用,我不知道其他哪种方式可以解决这个问题。

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);
    }
}

1 个答案:

答案 0 :(得分:0)

  1. Swing不是线程安全的,所有对UI的更新都必须在Event Dispatching Thread的上下文中进行。有关详细信息,请参阅Concurrency in Swing。在您的情况下,使用SwingWorker可能更容易,但我们会使用此...
  2. 您通常不鼓励直接从Thread扩展,我们鼓励您实施Runnable并将此实例传递给Thread的实例。
  3. 您可以通过使用某种锁来控制线程的执行。您可以使用原始的Object#waitObject#notify API,也可以使用更新的并发Lock API。为简单起见,我使用旧版本。有关详细信息,请查看Intrinsic Locks and SynchronizationLock Objects
  4. 需要由多个线程检查的变量应该是volatile,或者您应该使用等效的Atomic类之一。对于Atomic类,这可以确保对值的读取和写入干净地完成(一次只有一个线程)。看看Atomic Variables
  5. 例如......

    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);
                }
            });
        }
    
    }