GVKun编程网logo

SwingWorker没有响应(sw2010-2014 activator无法响应)

15

此处将为大家介绍关于SwingWorker没有响应的详细内容,并且为您解答有关sw2010-2014activator无法响应的相关问题,此外,我们还将为您介绍关于JavaGUI线程-SwingWor

此处将为大家介绍关于SwingWorker没有响应的详细内容,并且为您解答有关sw2010-2014 activator无法响应的相关问题,此外,我们还将为您介绍关于Java GUI线程-SwingWorker、Java Swingworker和多线程、java swingworker线程更新主GUI、Java – SwingWorker – 我们可以从其他SwingWorker而不是EDT调用一个SwingWorker的有用信息。

本文目录一览:

SwingWorker没有响应(sw2010-2014 activator无法响应)

SwingWorker没有响应(sw2010-2014 activator无法响应)

我要做什么?

单击时StartJButtonSwingWorker将执行。在doInBackground()方法内部,我将方法的每个索引传递arrNamespublish()方法,以便可以在中显示它JTextArea

发生了什么 ?

如果我 守行System.out.format("Counter : %d%n", counter);作为 注释
,在我doInBackground()的方法SwingWorker,则SwingWorker按预期工作 。尽管如果我将
其注释掉 ,则SwingWorker 停止响应

难道我做错了什么 ?


Java版本:

java version "1.7.0_25"Java(TM) SE Runtime Environment (build 1.7.0_25-b16)Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode, sharing)

这是我正在使用的代码:

import java.awt.*;import java.awt.event.*;import javax.swing.*;public class SwingWorkerExample1{    private JLabel statusLabel;    private JTextArea tArea;    private JButton startButton;    private JButton stopButton;    private BackgroundTask backgroundTask;    private ActionListener buttonActions =                            new ActionListener()    {        @Override        public void actionPerformed(ActionEvent ae)        {            JButton source = (JButton) ae.getSource();            if (source == startButton)            {                startButton.setEnabled(false);                stopButton.setEnabled(true);                backgroundTask = new BackgroundTask();                backgroundTask.execute();            }            else if (source == stopButton)            {                backgroundTask.cancel(true);                stopButton.setEnabled(false);                startButton.setEnabled(true);            }        }    };    private void displayGUI()    {        JFrame frame = new JFrame("Swing Worker Example");        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);        JPanel contentPane = new JPanel();        contentPane.setBorder(            BorderFactory.createEmptyBorder(5, 5, 5, 5));        contentPane.setLayout(new BorderLayout(5, 5));        statusLabel = new JLabel("Status Bar", JLabel.CENTER);        tArea = new JTextArea(20, 20);        tArea.setWrapStyleWord(true);        tArea.setLineWrap(true);                JScrollPane textScroller = new JScrollPane();        textScroller.setBorder(            BorderFactory.createTitledBorder("Textual OUTPUT : "));        textScroller.setViewportView(tArea);        startButton = new JButton("Start");        startButton.addActionListener(buttonActions);        stopButton = new JButton("Stop");        stopButton.setEnabled(false);        stopButton.addActionListener(buttonActions);        JPanel buttonPanel = new JPanel();        buttonPanel.add(startButton);        buttonPanel.add(stopButton);        contentPane.add(statusLabel, BorderLayout.PAGE_START);        contentPane.add(textScroller, BorderLayout.CENTER);        contentPane.add(buttonPanel, BorderLayout.PAGE_END);        frame.setContentPane(contentPane);        frame.pack();        frame.setLocationByPlatform(true);        frame.setVisible(true);    }    private class BackgroundTask extends SwingWorker<Void, String>    {        private int counter = 0;        private String[] arrNames = { "US Rates Strategy Cash",            "Pavan Wadhwa(1-212) 844-4597", "Srini Ramaswamy(1-212) 844-4983",            "Meera Chandan(1-212) 855-4555", "Kimberly Harano(1-212) 823-4996",            "Feng Deng(1-212) 855-2555", "US Rates Strategy Derivatives",            "Srini Ramaswamy(1-212) 811-4999",            "Alberto Iglesias(1-212) 898-5442",            "Praveen Korapaty(1-212) 812-3444", "Feng Deng(1-212) 812-2456",            "US Rates Strategy Derivatives", "Srini Ramaswamy(1-212) 822-4999",            "Alberto Iglesias(1-212) 822-5098",            "Praveen Korapaty(1-212) 812-3655", "Feng Deng(1-212) 899-2222" };        public BackgroundTask()        {            statusLabel.setText((this.getState()).toString());            System.out.println(this.getState());        }        @Override        protected Void doInBackground()        {            statusLabel.setText((this.getState()).toString());            System.out.println(this.getState());            while (!isCancelled())            {                counter %= arrNames.length;                //System.out.format("Counter : %d%n", counter);                publish(arrNames[counter]);                counter++;            }            statusLabel.setText((this.getState()).toString());            System.out.println(this.getState());            return null;        }        @Override        protected void process(java.util.List<String> messages)        {            for (String message : messages)                tArea.append(String.format(message + "%n"));        }    }    public static void main(String[] args)    {        Runnable runnable = new Runnable()        {            @Override            public void run()            {                new SwingWorkerExample1().displayGUI();            }        };        EventQueue.invokeLater(runnable);    }}

*编辑1:*

按照建议,如果我添加Thread.sleep(...),它确实可以工作,但是会抛出InterruptedException如下所示的错误。这样就可以了。但这是
合法 的表演方式吗?

C:\Mine\JAVA\J2SE\classes>java SwingWorkerExample1PENDINGSTARTEDjava.lang.InterruptedException: sleep interrupted        at java.lang.Thread.sleep(Native Method)        at SwingWorkerExample1$BackgroundTask.doInBackground(SwingWorkerExample1.java:108)        at SwingWorkerExample1$BackgroundTask.doInBackground(SwingWorkerExample1.java:76)        at javax.swing.SwingWorker$1.call(SwingWorker.java:296)        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)        at java.util.concurrent.FutureTask.run(FutureTask.java:166)        at javax.swing.SwingWorker.run(SwingWorker.java:335)        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)        at java.lang.Thread.run(Thread.java:724)DONE

编辑2:

只有doInBackground()被更改,从而引发了上述异常:

@Overrideprotected Void doInBackground(){    Runnable runnable = new Runnable()    {        @Override        public void run()        {            statusLabel.setText((BackgroundTask.this.getState()).toString());        }    };    EventQueue.invokeLater(runnable);    System.out.println(this.getState());    while (!isCancelled())    {        counter %= arrNames.length;                     //System.out.format("Counter : %d%n", counter);        publish(arrNames[counter]);        try        {Thread.sleep(30);}        catch(InterruptedException ie)        {ie.printStackTrace();}        counter++;    }    runnable = new Runnable()    {        @Override        public void run()        {            statusLabel.setText((BackgroundTask.this.getState()).toString());        }    };    EventQueue.invokeLater(runnable);    System.out.println(this.getState());    return null;}

答案1

小编典典

如果我添加Thread.sleep(…),它确实可以工作,但是会抛出InterruptedException

显然产生异常的代码(从OP的编辑中复制):

while (!isCancelled()) {    counter %= arrNames.length;    // System.out.format("Counter : %d%n", counter);    publish(arrNames[counter]);    try {        Thread.sleep(30); // throws    } catch (InterruptedException ie) {        ie.printStackTrace();    }    counter++;}

但是,原因是取消工作程序的代码(在actionListener中):

backgroundTask.cancel(true);

它明确告诉工作人员通过..中断线程来取消。从其api文档中:

mayInterruptIfRunning-如果应该中断执行此任务的线程,则为true;否则为false。否则,正在进行的任务将被允许完成

顺便说一句:捕获异常而不执行任何操作(从而有效地忽略中断)并不是最好的主意。在这种情况下,由于检查已取消状态,可能不会造成太大破坏。典型的工作程序实现要么在需要进行一些内部清理之后捕获并返回,要么根本不处理它。

Java GUI线程-SwingWorker

Java GUI线程-SwingWorker

我对SwingWorker和Java GUI有疑问。

我有几类,其处理的信息,我们可以给他们打电话Foo1Foo2Foo3。此处理可能需要很长时间。

这些都是的子类Foo,但是Foo本身并不是直接调用的(这些Foo[x]类使用继承自的方法Foo。为了使EDT自由绘制进度条,SwingWorker在保持对象层次结构时最好的使用方法是什么?是否具有包装器类,Foo1WorkerextendsSwingWorker并且有其doInBackground()调用Foo1.myProcessMethod()?即使Foo1不扩展SwingWorker,它仍然可以按我期望的那样工作吗?

编辑:澄清我的问题,Foo[x]即使他们已经是子类,我如何制作SwingWorkers?

答案1

小编典典

我认为答案关键取决于Foo子类管理的数据类型。如果结果是同质的,只需相应地扩展SwingWorker和实例化具体的子类:

class Whatever {}abstract class AbstractFoo extends SwingWorker<List<Whatever>, Whatever> {}class Foo1 extends AbstractFoo {    @Override    protected List<Whatever> doInBackground() throws Exception {        ...    }}

如果每个都管理不同的类型,则使父类通用,并使用所需的类型实例化每个具体的子类:

class Whatever {}class Whichever {}abstract class GenericAbstractFoo<T, V> extends SwingWorker<T, V> {}class Foo2 extends GenericAbstractFoo<List<Whatever>, Whatever> {    @Override    protected List<Whatever> doInBackground() throws Exception {        ...    }}class Foo3 extends GenericAbstractFoo<List<Whichever>, Whichever> {    @Override    protected List<Whichever> doInBackground() throws Exception {        ...    }}

Java Swingworker和多线程

Java Swingworker和多线程

我正在设计一个 Java GUI驱动的应用程序,该应用程序运行许多单独的任务,每个任务都在自己的SwingWorker扩展类中.这是我使用的正常设计,以便在自己的线程上运行任务,并且仍然可以让EDT免费更新GUI.每个SwingWorker都使用Executors.newCachedThreadPool在自己的线程上启动.

但是,在一个特定的类中,有一个任务需要相当长的时间来处理.该任务包含一个for循环,最多可执行六次计算.

我已经考虑过在自己的线程中实现六个计算中的每一个以加快处理时间,但我不确定实现它的最佳方法.

是否可以扩展SwingWorker并实现Runnable,然后在for循环中使用void Run()方法,每次启动一个新的Thread,或者使用cachedThreadPool.

或者我最好只使用标准的Thread()实现?

任何建议或意见将不胜感激.

提前致谢

玩笑

解决方法

user988052当然是正确的 – 如果你没有多核cpu,那么在六个不同的线程中进行计算实际上会减慢你的应用程序,因为线程的创建和管理带来了开销.

如果你想在六个独立的线程中进行这种计算,你可以使用SwingWorker作为管理线程,并在其中产生5-6个新线程.然后使用ExecutorService就可以了,因为它使用了一个线程池,从而最大限度地减少了创建和处理线程所带来的开销.

编辑:回答你的评论:

我认为最好的方法是在Runnable中实现计算(以便六个计算中的每一个可以单独运行),然后只需使用ExecutorService,实例化Runnablesix次并使用ExecutorService.submit(Runnable任务).您可以在SwingWorker.doInBackground()方法中完成所有这些操作.

你永远不应该自己调用run()方法 – 让它由Thread / ExecutorService完成.

java swingworker线程更新主GUI

java swingworker线程更新主GUI

您好,我想知道从swingworkerthread向jtextarea添加文本的最佳方法是什么,我创建了另一个类,Threadsclass()。execute()调用了jbutton。并且线程与此代码并行运行

public class Threadsclass extends SwingWorker<Object,Object> {


@Override
protected Object doInBackground() throws Exception {
    for(int x = 0; x< 10;x++)
        try {
            System.out.println("sleep number :"+ x);



        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(eftcespbillpaymentsThreads.class.getName()).log(Level.SEVERE,null,ex);
    }
    throw new UnsupportedOperationException("Not supported yet.");
}

}

现在id要做的是将x的值添加到主gui上的文本区域,任何想法都值得赞赏。

Java – SwingWorker – 我们可以从其他SwingWorker而不是EDT调用一个SwingWorker

Java – SwingWorker – 我们可以从其他SwingWorker而不是EDT调用一个SwingWorker

我有一个SwingWorker如下:

public class MainWorker extends SwingWorker(Void,MyObject) {
    :
    :
}

我从EDT调用了上面的Swing Worker:

MainWorker mainWorker = new MainWorker();
mainWorker.execute();

现在,mainWorker创建了MyTask类的10个实例,以便每个实例都可以在自己的线程上运行,从而更快地完成工作.

但问题是我想在任务运行时不时更新gui.我知道如果任务是由mainWorker本身执行的,我可以使用publish()和process()方法来更新gui.

但是由于任务是由不同于Swingworker线程的线程执行的,我如何从执行任务的线程生成的中间结果更新gui.

解决方法

SwingWorker的api文档提供了以下提示:

The doInBackground() method is called
on this thread. This is where all
background activities should happen.
To notify Propertychangelisteners
about bound properties changes use the
firePropertyChange and
getPropertyChangeSupport() methods. By
default there are two bound properties
available: state and progress.

MainWorker可以实现Propertychangelistener.然后它可以使用PropertyChangeSupport注册自己:

getPropertyChangeSupport().addPropertychangelistener( this );

MainWorker可以将其PropertyChangeSupport对象提供给它创建的每个MyTask对象.

new MyTask( ...,this.getPropertyChangeSupport() );

然后,MyTask对象可以使用PropertyChangeSupport.firePropertyChange方法通知其MainWorker进度或属性更新.

然后,通知的MainWorker可以使用SwingUtilities.invokelater或SwingUtilities.invokeAndWait通过EDT更新Swing组件.

protected Void doInBackground() {
    final int TASK_COUNT = 10;
    getPropertyChangeSupport().addPropertychangelistener(this);
    CountDownLatch latch = new CountDownLatch( TASK_COUNT ); // java.util.concurrent
    Collection<Thread> threads = new HashSet<Thread>();
    for (int i = 0; i < TASK_COUNT; i++) {
        MyTask task = new MyTask( ...,latch,this.getPropertyChangeSupport() ) );
        threads.add( new Thread( task ) );
    }
    for (Thread thread: threads) {
        thread.start();
    }
    latch.await();
    return null;
}

今天关于SwingWorker没有响应sw2010-2014 activator无法响应的分享就到这里,希望大家有所收获,若想了解更多关于Java GUI线程-SwingWorker、Java Swingworker和多线程、java swingworker线程更新主GUI、Java – SwingWorker – 我们可以从其他SwingWorker而不是EDT调用一个SwingWorker等相关知识,可以在本站进行查询。

本文标签: