线程可运行对象方法不响应更改

Threaded runnable object method not responding to changes

我有一个 class "HConnection" 包含多个方法,例如 abort();和 awaitConnection();

awaitConnection();使用可运行线程在我的 SWT Form main class 中调用方法。无论如何,当我中止 () HConnection 时,awaitConnection 没有中止,而它应该中止。

看看我的主要代码快照:

private HConnection connectie;

private void btnConnect_clicked(SelectionEvent e) {

    if (btnNewButton_1.getText().equals("Connect")) {
        String Url = combo.getText();
        connectie = new HConnection(Url);
        connectie.prepare();

        new Thread(new Runnable() {
              public void run() {
                    connectie.awaitConnection();

                    Display.getDefault().asyncExec(new Runnable() {
                        public void run() {
                            lblNewLabel_2.setText("Waiting -> client");
                            if (connectie.getState() == 2)  {
                                lblNewLabel_2.setText("Replacing URL");
                            }
                            else    {
                                lblNewLabel_2.setText("Failed");
                                connectie.abort();
                                btnNewButton_1.setText("Connect");
                            }
                        }
                    });
                    if (connectie.getState() == 2)  {
                        // go on

                    }
              }
        }).start();

        ////////

        btnNewButton_1.setText("Abort");
    }
    else if(btnNewButton_1.getText().equals("Abort"))   {
        connectie.abort();
        lblNewLabel_2.setText("Aborted");
        btnNewButton_1.setText("Connect");
    }

以及 HConnection 的快照:

public void prepare()   {
    addToHostsFile("127.0.0.1" + "\t" + domain);
    state = 1;
}

public void abort() {
    removeFromHostsFile("127.0.0.1" + "\t" + domain);
    waitingConnection = false;
    HostFileEdited = false;
    state = 0;
}

public void awaitConnection()   {
    if (state == 1) {
        waitingConnection = true;
        System.out.println("0");
        while (/* not found && */ state == 1)   {

            // code

        }
        System.out.println("1");
        waitingConnection = false;
        if (state == 1) state = 2;
    }

}

再补充一点;当我尝试在 thread.start() 之后直接调用 connectie.abort() 时,abort() 函数确实起作用并完成了线程;(在代码中放置了“////////”上面那个地方) 但是如果它在应该调用的地方调用,它就做它应该做的 而

lblNewLabel_2.setText("Aborted");
btnNewButton_1.setText("Connect");

正在按预期完成工作

使您的状态和 awaitConnection 可变:

private volatile int state;
private volatile boolean awaitConnection;