zoukankan      html  css  js  c++  java
  • (转)Swing中的并发使用SwingWorker线程模式

    http://zhangjunhd.blog.51cto.com/113473/34727 

    http://pope945.iteye.com/blog/263949 

    http://202.201.112.11/jpk/apply/teacher/preface/53/api/javax/swing/SwingWorker.html 

    个人觉得文笔最好思路最清晰来龙去脉交代得最明白也最浅显易懂的一篇文章: http://vearn.iteye.com/blog/344591

    当然,最牛B的详解文章往往都是英文版:http://java.sun.com/developer/technicalArticles/javase/swingworker/ 
     

    个人补充:

    1、在SwingWorker中调用非本类的其他方法时,这个方法也是在新线程(相对于事件派发线程EDT)中执行的。 比如下面的例子,

    当点击按钮时, 启用了一个SwingWorker()实例,这个对象调用了Test类的doSomething()方法,

    但输出的内容(System.out.println会输出false )表明,它的执行也是在新线程中的。 

    Class Test extends JFrame{

    private JButton button;

     public Test(){

                    button = new JButton("Run SwingWorker"); 

             button.addActionListener(new ActionListener(){

                              @override

                              public void actionPerformed(ActionEvent e){

                                         new SwingWorker(Integer,Void)(){

                                              @override

                                               protected Integer doInBackground() throws Exception(){

                                                          doSomething();

                                               } 

                                         }.execute();                                 

                              } 

                     }); 

             } 

             public Integer doSomething(){

    Integer i = 0;

                    System.out.println("doSomething() running in EDT?"+SwingUtilities.isEventDispatchThread()); 

     for(int j=0;j<=100000;j++){

     i++;

                    return i; 

             }

    2、给一个SwingWorker类起个名字这件事儿基本不需要,因为一个SwingWorker类是一次性的,也就是说它在cancal以后是无法再次execute()的。 

    3、如果你打算在doInBackground()中循环做一件事并不时刷新页面,可以考虑在doInBackground()的循环中publish(),这样你可以再写一个process()方法,在process()方法中你会得到publish发送的对象。

    4、SwingWorker的限制:最多十个。参考:http://www.jroller.com/ethdsy/entry/swingworker_is_not_a_thread

    修改线程池限制:

    sun.awt.AppContext.getAppContext().put(SwingWorker.class, Executors.newFixedThreadPool(100));
  • 相关阅读:
    Leetcode Binary Tree Preorder Traversal
    Leetcode Minimum Depth of Binary Tree
    Leetcode 148. Sort List
    Leetcode 61. Rotate List
    Leetcode 86. Partition List
    Leetcode 21. Merge Two Sorted Lists
    Leetcode 143. Reorder List
    J2EE项目应用开发过程中的易错点
    JNDI初认识
    奔腾的代码
  • 原文地址:https://www.cnblogs.com/mabaishui/p/2574455.html
Copyright © 2011-2022 走看看