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

时间:2016-11-19 13:35:01

标签: java multithreading runnable

我有一个包含多个方法的类“HConnection”,例如abort();和awaitConnection();

awaitConnection();使用runnable线程在我的SWT Form主类中调用方法。无论如何,当我中止()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");

按预期完成工作

1 个答案:

答案 0 :(得分:1)

使你的州和awaitConnection不稳定:

private volatile int state;
private volatile boolean awaitConnection;