1
有人可以解釋爲什麼當我嘗試運行2個或更多線程時,此程序中的窗口凍結?使用WindowBuilder SWT時在Java中的多線程
我希望能夠當兩個線程都運行在Hello按鈕點擊。 這是我的簡單項目。 任務類只打印出單詞「測試」。
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){}};
}
}
閉合類停止線程,當它在控制檯內鍵入停止。
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;
這裏是主窗口類的位置。
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");
}
}
你太棒了! – tijetof
謝謝@tijetof – maskacovnik