JavaSWT小部件是否影响线程性能?
我使用的是StyledText 400x100小部件,它的工作方式就像一个控制台,程序在控制台中与用户交互 以下是我更新小部件的方式:JavaSWT小部件是否影响线程性能?,java,multithreading,performance,widget,swt,Java,Multithreading,Performance,Widget,Swt,我使用的是StyledText 400x100小部件,它的工作方式就像一个控制台,程序在控制台中与用户交互 以下是我更新小部件的方式: private static Shell MainShell = null; public void createPartControl(Composite parent){ MainShell = parent.getShell(); } public static void updateConsole(final String newMessage
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() );
});
}
与append()类似,但这一行插入到第一行并插入换行符“\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();
}
//除以300/10,因为有一个内部for(),它每周期运行10个线程
对于(int n=0;n<300/10;n++){
//只允许10个线程工作
最终循环载体br=新循环载体(10);
对于(int i=0;i<10;i++){
新线程(新的MyClass(cb).start();
}
//等待线程到达屏障
等待;
}
现在是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();
}
}
public MyClass实现可运行{
专用循环载体cb;
公共MyClass(循环载波cb){
this.cb=cb;
}
@凌驾
公开募捐{
对于(int i=0;i<256;i++){
对于(int j=0;j<256;j++){
//视图是主类(EclipseRCP)并更新小部件
View.updateConsole(“矩阵[“+i+”][“+j+”]”);
//只是一个计算循环数的整数
View.TOTAL_LOOPS++;
}
}
cb.wait();
}
}
这是一个例子,它应该以异步方式(不是按顺序)写入视图小部件,因为线程没有按顺序到达屏障
我正在使用EclipseRCP(3.8)
问题
为什么程序在调试模式下工作正常?我在启动新线程的位置设置了一个断点(在内部for()中),并单击“恢复”按钮逐个启动线程。
当我试图在正常模式下打开(运行或导出)时,会出现“泄漏”(我不知道如何命名),控制台中的行数较少。
View.TOTAL_循环
总共应具备:
256*256*10*30=19660800//View.TOTAL_LOOPS++;在MyClass中
在正常运行时,它会产生动态结果:174614904、17025759等。在调试模式下,它会达到精确的值
问题:
线程是否被终止?这与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,如果逐个启动线程,显然不会发生这种情况
如果您只需要线程安全计数器或以其他方式正确同步线程,请使用原子整数