首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AWT事件线程中断

AWT事件线程中断
EN

Stack Overflow用户
提问于 2011-10-05 04:38:30
回答 1查看 255关注 0票数 2

我有代码:

代码语言:javascript
复制
import java.awt.Dimension;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class Test2 {

JFrame frame = null;
JPanel panel = null;
JButton button = null;
Task task = null;
Indicator indicator = null;
Runnable computation;

public static void main(String[] args) {
    new Test2().start();
}

public void start() {
    SwingUtilities.invokeLater(new Dialog());
}

private void process1() {
    int result = 0;

    for (int i=0; i<100000; i++) {
        result = (int) Math.ceil(++result + Math.sqrt(result));

        System.out.println("proc1 " + result);
    }
}

private void process2() {
    int result = 0;

    for (int i=0; i<100000; i++) {
        result = (int) Math.ceil(++result + Math.sqrt(result)*500);

        System.out.println("proc2 " + result);
    }
}

private class Computation implements Runnable {

    public void run() {

        process1();
        task.setProgress(2);
        process2();
        task.setProgress(3);
    }

}

private class Dialog implements Runnable {

    public Dialog() {
    }

    public void run() {
        frame = new JFrame("Test");
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(300, 200));
        frame.getContentPane().add(panel);
        button = new JButton("b1");
        panel.add(button);
        indicator = new Indicator();
        task = new Task();
        task.addObserver(indicator);

        frame.pack();
        frame.setVisible(true);

        computation = new Computation();
        SwingUtilities.invokeLater(computation);
    }
}

private class Task extends Observable {

    int progress;

    public Task() {

    }

    public void setProgress(int progress) {
        this.progress = progress;
        setChanged();
        notifyObservers();
    }

    public int getProgress() {
        return progress;
    }
}

private class Indicator implements Observer {

    @Override
    public void update(Observable arg0, Object arg1) {
        button.setText(((Task)arg0).getProgress()+"");
    }
}
}

问题在于,更新是在process1()和process2()完成之后执行的。

EN

回答 1

Stack Overflow用户

发布于 2011-10-05 05:04:03

..update在process1()和process2()完成后执行。

不要在EDT上执行长时间运行的任务,有关详细信息,请参阅Concurrency in Swing。实现这一点的一种方法是使用SwingWorker

..if我使用两个SwingWorkers来执行process1()process2(),那么它们的执行顺序是不可预测的。我需要process1()跟踪process2()。我怎样才能得到这个?

在1 SwingWorkerdoInBackground()方法中调用这两个方法,并在适当的时候使用适当的值调用SwingWorker.setProgress(int)。例如。

代码语言:javascript
复制
... doInBackground() {
    setProgress(0);
    process1();
    setProgress(50);
    process2();
    setProgress(100);
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7653746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档