gpt4 book ai didi

java - SWT 后台线程阻塞 GUI

转载 作者:行者123 更新时间:2023-12-02 05:17:15 24 4
gpt4 key购买 nike

下面的代码阻塞了我的用户界面,我检查了其他帖子,这似乎是正确的实现,请让我知道我在这里做错了什么:

public class RecordTest {

public static boolean stopFlag=false;
public static void main(String[] args) {

Display display = Display.getDefault();
Shell shell = new Shell (display);
Label label = new Label (shell, SWT.NONE);
label.setText ("Enter your URL:");
final Text text = new Text (shell, SWT.BORDER);
text.setLayoutData (new RowData (100, SWT.DEFAULT));
Button ok = new Button (shell, SWT.PUSH);
ok.setText ("Start Record");

Thread updateThread = new Thread() {
public void run() {
Display.getDefault().asyncExec(new Recorder(stopFlag));
}
};
// background thread
updateThread.setDaemon(true);
updateThread.start();



ok.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Start Record");

}
});
Button cancel = new Button (shell, SWT.PUSH);
cancel.setText ("Stop Recording");
cancel.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Stop Recording");
stopFlag=true;
}
});
shell.setDefaultButton (cancel);
shell.setLayout (new RowLayout ());
shell.pack ();
shell.open ();
while (!shell.isDisposed ()) {
if (!display.readAndDispatch ()) display.sleep ();
}
display.dispose ();
}
}

------------------------------------Recorder.java-------- ---------------------------------

public class Recorder implements Runnable {

private boolean stopFlag = false;

public Recorder(boolean stopFlag) {
this.stopFlag = stopFlag;
}

@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
System.out.println("Waiting ....");
Thread.sleep(3000);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

最佳答案

好吧,您在线程中使用 Display.asyncExec(...) ,这意味着 Recorder.run() 的代码在 UI 线程中运行...这会阻塞 UI 线程中的所有事件处理。

基本规则是 run 方法必须在几毫秒内完成!

关于java - SWT 后台线程阻塞 GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26821099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com