从按钮单击事件启动线程时,Gui被阻止 [英] Gui blocked when starting Thread from button clicked event

查看:82
本文介绍了从按钮单击事件启动线程时,Gui被阻止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个基本问题,但我坚持使用。

This may be a basic question but one that I am stuck on.

我想更多地了解为什么在我开始新线程时GUI被阻止(runnable)来自按钮点击事件?我该如何克服这个问题?我做错了什么?

I would like some more understanding on why the GUI is blocked when I start a new thread(runnable) from a button click event? and how do I overcome that? What am I doing wrong?

下面的代码在单击时会启动一个新线程,但是我想在单击该按钮时更改文本框的背景颜色但我无法做到这一点,主要的ui在线程运行时没有响应,我相信我正在通过启动一个新线程来正确实现它,以便不阻止主要的ui,但我一定错过了一些东西,因为这显然不是理想的行为。

The code below starts a new thread when it is clicked, however I would like to change the background color of a textbox when that button is clicked but I am unable to do that, also the main ui is unresponsive whilst that thread is running, I believed that I was implementing it correctly by starting a new thread so as to NOT block the main ui but I must have missed something out as this obviously not desired behaviour.

代码:

private void startButtonEvent(ActionEvent evt) {

         ntmStatusText.setBackground(Color.green);// textbackground I want to change

        //Start Ntm Thread
         Thread thread = new Thread(new NtmThread());
           thread.start();

           while(thread.isAlive()){

               System.out.println("thread still working");

           }
           System.out.println("thread stopped");

    }

如何在运行线程时阻止我的Ui无响应?

How do I stop my Ui from becoming unresponsive when running threads?

推荐答案

while(thread.isAlive()){是一个阻塞方法,它将停止事件调度线程,直到 Thread.isAlive 变为false,这会阻止它处理已添加到事件队列的新事件,包括绘制请求

while(thread.isAlive()){ is a blocking method, it will stop the Event Dispatching Thread until Thread.isAlive becomes false, this prevents it from been able to process new events that are been added to the event queue, including paint requests

这是因为Swing是一个单线程环境,这意味着有一个线程负责处理进入程序的所有事件。这由事件调度线程处理。

This occurs because Swing is a single threaded environment, meaning that there is a single thread responsible for process all events coming into the program. This is handled by the Event Dispatching Thread.

所有用户生成的事件都在EDT内管理(即,你 actionPerformed 方法,在EDT的上下文中调用)

All user generated events are managed within the EDT (that is, you actionPerformed method, is called within the context of the EDT)

Swing中的并发性

您可以为 NtmThread <提供回调功能/ code>或考虑使用 SwingWorker 并将 PropertyChanegListener 附加到该属性的监视器并检查 SwingWorker 的状态是否已更改为 DONE

You eaither theen to provide a call back functionality to your NtmThread or consider using a SwingWorker and attaching a PropertyChanegListener to it a monitor for the property state and check that the SwingWorkers state has changed to DONE

请参阅工人Threads和SwingWorker 了解更多详情

例如:如何使用jProgress栏进行ProcessBuilder流程?

这篇关于从按钮单击事件启动线程时,Gui被阻止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆