簡體   English   中英

AWT事件線程中斷

[英]AWT event thread interruption

我有代碼:

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)。 我的目標是在process1完成之后,更新擺動按鈕(請參閱task.setProgress方法)。

問題在於更新是在process1()和process2()完成之后執行的。

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

不要在EDT上執行長時間運行的任務,有關詳細信息,請參見Swing中的並發 一種實現方法是使用SwingWorker


..如果我使用兩個SwingWorkers來執行process1()process1() process2() ,則它們的執行順序是不可預測的。 我需要process2()通過如下process1() 我怎么能得到這個?

在1 SwingWorkerdoInBackground()方法中調用這兩個方法,並在適當的時候使用適當的值調用SwingWorker.setProgress(int) 例如

... doInBackground() {
    setProgress(0);
    process1();
    setProgress(50);
    process2();
    setProgress(100);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM