【问题标题】:Java: How will I be able to create a Stop JButton which will stop the Runnable() thread?Java:我将如何创建一个停止 Runnable() 线程的 Stop JButton?
【发布时间】:2016-02-08 03:24:38
【问题描述】:

我使用接受浏览器请求的 ServerSocket 在 Java 中创建了一个简单的 HTTP 服务器。服务器工作正常,没有任何错误。我使用 Swing 创建了一个 JForm,其中包含用于启动和停止服务器的按钮。在开始按钮中,我添加了一个运行 ServerMain 类的 ActionListener。

btnStartServer.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
    try {
        new Thread(new Runnable() {
            public void run() { 
                ServerMain.main(new String[0]);
            }
         }).start();
        } catch (Exception e) {
        e.printStackTrace();
    }
}});

如何创建一个停止 Runnable() 线程的 Stop JButton?

【问题讨论】:

  • 你能分享ServerMain.main()代码吗?
  • 没有保证停止Thread 的方法,然后在线程中编写代码以支持它。您的服务器应该正在监视当前线程的中断状态,并且您应该有一个标志(可能是 AtomicBoolean),您可以更改并检查其状态以确定线程的状态

标签: java multithreading swing


【解决方案1】:

在实现Future<V>cancel() 方法的类的上下文中运行服务器。 SwingWorker<T,V>就是这样一个RunnableFuture<V>;一个完整的例子见here

【讨论】:

    【解决方案2】:

    你不想仅仅杀死一个线程(通过使用Thread.stop())。原因列在this article

    我假设ServerMain.main(String... args) 中的代码运行某种while(condition) 循环,如下所示:

    public class ServerMain{
        public static boolean condition = true;
    
        public static void main(String... args){
            while(condition){
                //do stuff
            }
            //close sockets and other streams.
            //Call Thread.interupt() on all sleeping threads
        }
    }
    

    您的按钮应该以某种方式将此条件设置为 false:

    stopButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            try {
                new Thread() {
                    public void run() {
                        // set condition to false;
                        ServerMain.condition = false;
                    }
                }.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      相关资源
      最近更新 更多