(转)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));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值