2016-11-19 74 views
0

我有一個包含多種方法(如abort())的類「HConnection」。和awaitConnection();線程可運行對象方法對變化沒有響應

awaitConnection();方法在我的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"); 

正在做他們的工作預期

+0

也許你的else塊內run()方法沒有得到執行 –

+0

@VikasSachdeva沒有多數民衆贊成沒有問題 – JonasAnon

+1

有時線程不會立即開始,所以當你在你的線程調用'start'之後調用中止,'awaitConnection()'甚至可能不會被調用 –

回答

1

讓你的狀態和awaitConnection揮發性:

private volatile int state; 
private volatile boolean awaitConnection; 
+0

這樣做了!謝謝 – JonasAnon