gpt4 book ai didi

java - 使用 WindowBuilder SWT 时 Java 中的多线程

转载 作者:行者123 更新时间:2023-11-30 08:04:22 25 4
gpt4 key购买 nike

有人可以解释一下为什么当我尝试运行 2 个或更多线程时该程序中的窗口会卡住吗?

我希望能够在两个线程都运行时单击“Hello”按钮。这是我的简单项目。任务类仅打印出单词“Testing”。

public class Task extends Thread {
public static boolean keepRun = true;

public void run(){
while(keepRun == true){
System.out.println("Testing...");

try {
Thread.sleep(1000);
}catch(InterruptedException e){}};
}
}

当在控制台内键入 stop 时,关闭类会停止线程。

import java.util.Scanner;
public class Closing implements Runnable{
Scanner s = new Scanner(System.in);
public void run() {

while (s.next().equals("stop")){
System.out.println("Threads down");

Task.keepRun =false;

try {
Thread.sleep(5000);
}catch(InterruptedException e){}
};

}
}

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

这是 Window 类,main 也位于其中。

public class Window {

protected Shell shell;

/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Window window = new Window();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}

/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell.setSize(192, 208);
shell.setText("SWT Application");

Button btnRun = new Button(shell, SWT.NONE);
btnRun.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Task newTask = new Task();
Closing closing = new Closing();
newTask.start();
closing.run();
}
});
btnRun.setBounds(50, 32, 75, 25);
btnRun.setText("Run");

Button btnHello = new Button(shell, SWT.NONE);
btnHello.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("Hello");
}
});
btnHello.setBounds(50, 81, 75, 25);
btnHello.setText("Hello");

}
}

最佳答案

重写这个:

Closing closing = new Closing();
newTask.start();
closing.run();

对此:

Closing closing = new Closing();
newTask.start();
new Thread(closing).start();

看看这段代码:

public class Closing implements Runnable{
Scanner s = new Scanner(System.in);
public void run() {

while (s.next().equals("stop")){
System.out.println("Threads down");

Task.keepRun =false;

try {
Thread.sleep(5000);
}catch(InterruptedException e){}
};
}
}

如果你简单地调用run();Thread.sleep(5000);将影响调用run的线程,另一方面,当你创建一个新的线程, sleep 会受到这个线程的影响。

关于java - 使用 WindowBuilder SWT 时 Java 中的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31368109/

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