java - 如何从另一个线程暂停和恢复 Java 中的线程

标签 java multithreading swing

我正在使用 Java Swing 编写应用程序。我需要的是一个程序,我可以使用图形界面中的按钮停止“细化”线程。

这里是一个简单的项目,专注于我需要的东西

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextArea;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Nikola
 */
public class Main extends javax.swing.JFrame
{
    private MyThread THREAD;

    public Main()
    {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Pause Thread");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButton2.setText("Resume Thread");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Start Thread");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt)
    {
        THREAD = new MyThread(jTextArea1);
        THREAD.start();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
    {
        try
        {
            THREAD.pauseThread();
        }
        catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
    {
        THREAD.resumeThread();
    }

    public static void main(String args[])
    {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try
        {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
            {
                if ("Nimbus".equals(info.getName()))
                {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        }
        catch (ClassNotFoundException ex)
        {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (InstantiationException ex)
        {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (IllegalAccessException ex)
        {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        catch (javax.swing.UnsupportedLookAndFeelException ex)
        {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable()
        {

            public void run()
            {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration
}

class MyThread extends Thread
{
    JTextArea area;

    private final Object lock = new Object();

    public MyThread(JTextArea area)
    {
        super();
        this.area = area;
    }

    @Override
    public void run()
    {
        for(int i=0 ; ; i++)
            area.setText(i+"");
    }

    public void pauseThread() throws InterruptedException
    {
        synchronized(lock)
        {
            lock.wait();
        }
    }

    public void resumeThread()
    {
        synchronized(lock)
        {
            lock.notify();
        }
    }
}

问题很简单: 在实际应用中,用户设置一些选项,然后启动对所选数据进行细化的线程。

我想提供一个“暂停”按钮,以便用户可以暂时停止细化并进行一些必要的检查,然后可以恢复操作。

在我编码的方式中,停止的是图形线程,而不是“详细说明”线程。

如果您运行我的示例代码并按“开始”,文本区域将开始计数。我需要的最终结果是当我按下“暂停”按钮时线程进入“ sleep ”并且计数停止,当我按下“恢复”按钮时线程“醒来”并且文本区域中的计数开始反对计数。

最佳答案

您不能明确地以您想要的方式暂停一个线程与另一个线程。

相反,您需要做的是通过设置某种标志信号其他线程应该停止。有问题的线程必须具有检查此标志并在发生这种情况时暂停其工作的逻辑。

所以在这种特殊情况下,也许可以如下更改 MyThread:

class MyThread extends Thread {

    private volatile boolean running = true; // Run unless told to pause

    ...

    @Override
    public void run()
    {
        for(int i=0 ; ; i++)
        {
            // Only keep painting while "running" is true
            // This is a crude implementation of pausing the thread
            while (!running)
                yield;

            area.setText(i+"");
    }

    public void pauseThread() throws InterruptedException
    {
        running = false;
    }

    public void resumeThread()
    {
        running = true;
    }

}

这是一个粗略的例子,为简洁起见,使用了一种自旋锁,而不是适当的基于监视器的 hibernate 。希望它传达了如何使用标志来控制线程暂停的想法。

请注意,如果您在 block 中执行一些长时间运行的步骤集,而不仅仅是 setText 调用,则最好检查 Thread.currentThread()。在每个步骤之间执行 interrupted() - 如果设置了 itnerrupt 标志,则退出循环。这大致就是内置阻塞方法(例如 I/O)所做的,以便它们可以被其他线程中断——因为 running 标志在每个循环中只检查一个,它不会做如果每个循环需要 20 分钟,则设置它非常好。

关于java - 如何从另一个线程暂停和恢复 Java 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989589/

相关文章:

java - 关于线程的wait()/notify

java - JTextArea - 如何在指定偏移处设置文本?

java - 如何在 JFrame 的 paint() 函数之外绘制图形

java - HQL 按时间单位(小时/天/月)选择总和和时间组以及

java - 用于持续测试的代码结构

java - 如何在maven中处理多个测试环境?

c++ - 人们实际上使用什么无锁原语在c++中进行无锁音频处理?

java - 在Java中创建数组的数组

python - 检查线程/从列表中删除

java - JApplet - super.paint();导致闪烁