gpt4 book ai didi

java - 在适当的时候更新线程

转载 作者:行者123 更新时间:2023-11-30 03:38:41 25 4
gpt4 key购买 nike

我在让我的线程 100% 正确工作方面遇到了问题,因为目前它返回的是已经排序的图表,即使我在排序算法中更新线程时它仍在排序。也许我可能缺少一段代码,因为我觉得我现在就拥有它了。

private class ButtonHandler implements ActionListener
{

public void actionPerformed(ActionEvent e)
{
Object src = e.getSource();
if (src == button1){

int[] array2=array;
for (int i = 1; i < array2.length; i++) {
int thingToInsert = array2[i];

int j = i - 1;
while (j >= 0 && thingToInsert<array2[j]) {
array2[j+1] = array2[j];
j--;
}

array2[j+1] = thingToInsert;
(new UpdateTextFieldThread()).execute();
}

}
}

}

 private class UpdateTextFieldThread extends SwingWorker<Void, Integer> 
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
ExecutorService service = Executors.newSingleThreadExecuto();
try {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(THREAD_DELAY);
display.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Future<?> f = service.submit(r);

f.get(2, TimeUnit.MINUTES);
}
catch (final InterruptedException e) {
// The thread was interrupted during sleep, wait or join
}
catch (final TimeoutException e) {
// Took too long!
}
catch (final ExecutionException e) {
// An exception from within the Runnable task
}
finally {
service.shutdown();
}
return null;




}

这就是我为实现我想要的目标而所做的。

  private class UpdateTextFieldThread extends SwingWorker<Void, Integer[]> 
{
static final int THREAD_DELAY = 1000;
protected Void doInBackground()
{
if(base==1){
array2=array;
try {

Integer[] array3=array;
for (int i = 1; i < array3.length; i++) {
Thread.sleep(THREAD_DELAY);

int thingToInsert = array3[i];

int j = i - 1;
while (j >= 0 && thingToInsert<array3[j]) {
array3[j+1] = array3[j];
j--;
}

array3[j+1] = thingToInsert;
publish(array3);
}



} catch (InterruptedException e) {
e.printStackTrace();
}
}

return null;
}
protected void process(java.util.List<Integer[]> list)
{
array2=list.get(list.size()-1);

display.repaint();
}
}

最佳答案

看起来你把这个问题搞得太复杂了!您有一个 SwingWorker,它在后台线程上执行;然后就开始了它自己的另一个线程。

我认为您希望您的 ActionListener 启动 SwingWorker 来进行排序,并且可以使用 SwingUtilities.invokeLater() 来安排只要有需要就重新粉刷。或者在 process() 方法中进行更新,并调用 publish() 来触发重绘。

关于java - 在适当的时候更新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27255244/

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