简体   繁体   English

线程停止,挂起和恢复

[英]Threads stopping, suspending, and resuming

I'm writing a code that involves JFrame, and a thread. 我正在编写一个涉及JFrame和一个线程的代码。 The thread should take the text from a text field and write it into text area. 该线程应从文本字段中获取文本并将其写入文本区域。 I have 4 buttons as follows: 我有4个按钮,如下所示:

  1. "Start" to start the thread. “启动”以启动线程。
  2. "Stop" which stops the thread. “停止”停止线程。
  3. "Pause" which pause and continues the thread. “暂停”可暂停并继续执行线程。
  4. and "Exit" which stops the thread and exits the program. 和“退出”停止线程并退出程序。

I've created the thread and implemented "run()" function in frame's constructor, here it is: 我创建了线程并在框架的构造函数中实现了“ run()”函数,它是:

WritingThread = new Thread(new Runnable() {
    @Override
    public void run() {
        String s = WrittenText.getText();
        while(true)
        {
            for(int i = 0; i < 4; i++)
            {
                for(int j = 0; j < s.length(); j++)
                {
                    WritingArea.append("" + s.charAt(j));
                    try {
                        Thread.sleep((int)ThreadSpeedSpinner.getValue());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }   
                }
                WritingArea.append("\n");
            }   
            WritingArea.setText("");
        }
    }
});

and these are the buttons: 这些是按钮:

JButton btnStart = new JButton("Start");
btnStart.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if(!WritingThread.isAlive())
            WritingThread.start();
    }
});
JButton btnStop = new JButton("Stop");
btnStop.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if(WritingThread.isAlive())
            WritingThread.stop();
    }
});
btnPause = new JButton("Pause");
btnPause.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        if(!isPaused)
        {
            if(WritingThread.isAlive())
            {
                WritingThread.suspend();
                btnPause.setText("Continue");
                isPaused = true;
            }
        }
        else
        {
            WritingThread.resume();
            btnPause.setText("Pause");
        }
    }
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        WritingThread.stop();
        System.exit(0);
    }
});

I have two problems showing up: 我出现两个问题:

  1. When I use stop() , suspend() , or resume() , I get a warning says "The method from the type Thread is deprecated". 当我使用stop()suspend()resume() ,我收到一条警告,提示“不赞成使用Thread类型的方法”。
  2. When I run the program, I start the thread, then stop it, then try to start it I have this exception 当我运行程序时,我启动线程,然后停止它,然后尝试启动它,我有这个异常

     Exception in thread "AWT-EventQueue-0" java.lang.IllegalThreadStateException at java.lang.Thread.start(Unknown Source) at com.HomeWork.HomeWork5$6.actionPerformed(HomeWork5.java:140) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$200(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source) 

I don't want direct answers, I want to understand why I'm getting these errors, and if there any resources I should go through. 我不想要直接的答案,我想了解为什么我会遇到这些错误,以及是否应该经历任何资源。 PS I searched for an answer a lot and didn't get anything explaining this problem. PS我搜索了很多答案,但没有得到任何解释此问题的信息。 Thanks 谢谢

Threads acquire lock on objects. 线程获取对象上的锁。 And the most important part of multithreading is to safely interweave the threads, so that all the threads can use the resource (object). 多线程的最重要部分是安全地交织线程,以便所有线程都可以使用资源(对象)。 If not dealt with correctly, it leads to deadlock . 如果处理不当,则会导致死锁

When you use stop() , you are killing the thread. 使用stop() ,您正在杀死线程。 That thread is gone forever. 那个线程永远消失了。 It may lead the objects, that stopped thread had acquired, in a inconsistent state . 它可能导致处于停止状态的对象(已停止线程已获取)。

suspend() is deprecated, because once the thread is suspended other threads won't get the resource, since the suspended thread holds a lock on it. 不建议使用suspend() ,因为一旦线程被挂起,其他线程将无法获取资源,因为被挂起的线程对其保持了锁定。

The image below describes how threads should be correctly used. 下图描述了如何正确使用线程。 Use sleep() , wait() , and notify() for interleaving the threads efficiently. 使用sleep()wait()notify()可以有效地交错线程。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM