如何获得当前运行代码的SwingWorker?

时间:2012-04-27 15:21:23

标签: java multithreading swing swingworker

如何获得当前正在运行的代码SwingWorker?您可以使用Thread.currentThread()获取Thread实例,但我需要SwingWorker实例。

评论中的代码

private static void loadFeaturesForSym(final SeqSymmetry optimized_sym, 
                                       final GenericFeature feature) 
  throws OutOfMemoryError { 
  final CThreadWorker<Boolean, Object> worker = 
     new CThreadWorker<Boolean, Object>("Loading feature " + feature.featureName) { 
         @Override 
         protected Boolean runInBackground() { 
           try { 
             return loadFeaturesForSym(feature, optimized_sym); 
           } catch (Exception ex) { 
             ex.printStackTrace(); 
           } 
           return false; 
         } 
       }; 
       ThreadHandler.getThreadHandler().execute(feature, worker); 
     } 
   }

1 个答案:

答案 0 :(得分:2)

我建议您创建SwingWorker可以侦听的模型对象,并将这些更新发布到发布和处理方法中。您的其他对象不应该了解SwingWorker,他们应该只知道自己的进度并将其发布给想听的人。它被称为解耦。这是实现它的一个想法,它使用了接近MVC的东西。我没有编译这段代码,但它有助于解释我在说什么。

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

public class ProcessStatus {
    public static final String PROGRESS = "Progress";

    private PropertyChangeSupport propertyChangeSupport;

    private int progress = 0;

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
        propertyChangeSupport.firePropertyChange(propertyName, oldValue, newValue);
    }

    public void setProgress(int progress) {
        int oldProgress = progress;
        this.progress = progress;
        firePropertyChange(PROGRESS, oldProgress, progress);
    }

    public int getProgress() {
        return progress;
    }
}

public class SomeWorker extends SwingWorker implements PropertyChangeListener {
    public void doInBackground() {
        ProcessStatus status = new ProcessStatus();
        status.addPropertyChangeListener(this);
        ProcessorThingy processor = new ProcessorThingy(status);
        processor.doStuff();
    }

    public void propertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(ProcessStatus.PROGRESS)) {
            publish((Integer) evt.getNewValue());
        }
    }
}

public class ProcessorThingy {
    private ProcessStatus status;

    public ProcessorThingy(ProcessStatus status) {
        this.status = status;
    }

    public void doStuff() {
        //stuff part 1
        status.setProgress(10);
        //stuff part 2
        status.setProgress(50);
        //stuff part 3
        status.setProgress(100);
    }
}