2013-02-12 25 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

相关问题