gpt4 book ai didi

java - Java SWT Widgets 会影响线程性能吗?

转载 作者:行者123 更新时间:2023-11-30 09:26:47 25 4
gpt4 key购买 nike

我正在使用 StyledText 400x100 小部件,它的工作方式就像一个控制台,程序可以在其中与用户交互。

这是我更新小部件的方式:

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();
}

现在是 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();
}
}

这是一个例子。它应该以异步方式(不按顺序)写入 View 小部件,因为线程没有按顺序到达屏障。

我正在使用 eclipse RCP (3.8)。

问题

为什么程序在 DEBUG 模式下运行正常?我在开始新线程的地方设置了一个断点(在内部 for() 中),然后单击 Resume 按钮一个接一个地启动线程。当我尝试以正常模式(运行或导出)打开时,出现“泄漏”(我不知道如何命名),控制台中的行数较少。 查看.TOTAL_LOOPS总共应该有:

256*256*10*30 = 19660800 // View.TOTAL_LOOPS++; in the MyClass

在正常运行中它有动态结果:174614904、17025759 等。在 DEBUG 模式下它达到精确值。

问题:

线程是否被杀死?

最佳答案

与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

关于java - Java SWT Widgets 会影响线程性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com