2013-02-12 27 views
2

我正在使用StyledText 400x100小部件,它的工作方式類似於程序與用戶交互的控制檯。Java SWT Widgets是否影響線程性能?

這是我如何更新插件:

private static Shell MainShell = null; 

public void createPartControl(Composite parent){ 
    MainShell = parent.getShell(); 
} 

public static void updateConsole(final String newMessage){ 
    if(MainShell.isDisposed() || myStyledText.isDisposed()) return; 

    MainShell.getDisplay().syncExec(new Runnable(){ 
     myStyledText.setText(newMessage + "\n" + myStyledText.getText()); 
    }); 
} 

類似追加(),但是這一次插入到第一行,並插入一個換行符「\ n」。

我正在使用CycleBarrier來處理線程。目前它運行着300多個線程,我只允許10個線程/週期不殺死CPU。

// divide 300/10 because there is an inner for() which runs 10 threads/cycle 
for(int n = 0; n < 300/10; n++){ 

    // allow only 10 threads to work 
    final CycleBarrier br = new CycleBarrier(10); 

    for(int i = 0; i < 10; i++){ 
     new Thread(new MyClass(cb).start(); 
    } 

    //waiting for Threads to reach the barrier 
    br.await(); 
} 

而且現在MyClass的類:

public MyClass implements Runnable{ 
    private CycleBarrier cb; 

    public MyClass(CycleBarrier cb){ 
     this.cb = cb; 
    } 

    @Override 
    public void run(){ 
     for(int i = 0; i < 256; i++){ 
     for(int j = 0; j < 256; j++){ 
      //View is the main class (eclipse RCP) and updateing the widget 
      View.updateConsole("matrix["+i+"]["+j+"]"); 

      // Just an integer which counts the number of the loops 
      View.TOTAL_LOOPS++; 
     } 
     } 
     cb.await(); 
    } 
} 

這是一個例子。它應該以異步方式(不按順序)寫入視圖窗口小部件,因爲線程沒有按順序到達屏障。

我使用eclipse RCP(3.8)。

發行

爲什麼程序在調試模式下工作是否正確?我已經在開始新線程的位置(在()的內部)設置了一個斷點,並且我單擊了繼續按鈕以逐個啓動線程。 當我試圖以正常模式(運行或導出)打開時出現「泄漏」(我不知道如何命名),控制檯中的行數較少。 View.TOTAL_LOOPS 應該有總數:

256 * 256 * 10 * 30 = 19660800個// View.TOTAL_LOOPS ++;在MyClass中

並且在正常運行中它具有動態結果:174614904,17025759等。在DEBUG模式下,它達到了確切的值。

問:

是線程被殺害?

回答

2

它與SWT無關。您正在從10個線程增加一個共享變量。這是一個競爭條件的典型例子。由於++不是一個原子操作,這樣的事情可能發生:

int temp = View.TOTAL_LOOPS; // in thread 1 
int temp = View.TOTAL_LOOPS; // in thread 2 
int temp2 = temp + 1; // in thread 1 
View.TOTAL_LOOPS = temp2; // in thread 1 
int temp2 = temp + 1; // in thread 2 
View.TOTAL_LOOPS = temp2; // in thread 2 

View.TOTAL_LOOPS只有1在這之後增加,顯然,如果你啓動一個線程按一個它不會發生。

如果您只是想要一個線程安全計數器或正確同步您的線程,請改用AtomicInteger

相關問題