为什么总是说,把更新Swing组件的任务一定要交给事件派发线程(EDT),而在此线程之外的独立线程中更新UI却是运行不正常的??我一直都是按后者的方法去实现复杂的逻辑运算和UI的更新,运行都很正常啊??~~~
大家一起讨论啊~~

解决方案 »

  1.   

    不要在EDT里执行耗时的任务,会导致GUI响应迟钝。Swing程序慢的许多恶名就是因此而来的。
      

  2.   


    当然,必须不要在EDT里执行耗时任务但是现在又有了个疑点public void actionPerformed(ActionEvent e) 
    {
      new Thread(ABC).start();}这个事件里面的线程ABC 到底也算在EDT线程里面的,还是算EDT之外的独立线程?
      

  3.   

    始终记住线程是并行运行的。我原来在国外Oracle java forum看的:
    6. Why does not the initial thread simply create the GUI itself? Because almost all code that creates or interacts with Swing components must run on the event dispatch thread. Why? Because Swing event handling code runs on a special thread known as the event dispatch thread, the creation of GUI must be invoked from the same thread (EDT). This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labeled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.这个很好的回答了你的问题。
      

  4.   


    楼主的问题属于多线程知识的范畴。简单的说,有这样一句话: 可变数据必须在一个线程安全的环境下访问。线程安全的实现手段很多,最简单的一种简化方案就是: 保证数据只在单线程中访问。这就是为什么几乎所有的UI框架都设计为单线程的原因。 这种手段叫做 Thread Confinement(线程约束)。这是因为UI系统本身已经非常复杂,可变数据非常多,如果用通常的加锁等手段对它们分别保护的话,会非常的复杂,——思考一下简化方案的话,就是整个系统所有的可变数据都用同一把锁,然后你就发现,用同一把锁实际上对整个UI系统的访问就是一个虚拟的“单线程”,而且还加上了加锁的内存同步成本,于是更好的方案就显而易见了:干脆用一个专门的线程,——这个线程就是EDT。
      

  5.   

    比如需要一遍查询数据库,一边把数据库内容在界面上显示的时候,如果查询数据库的操作放在EDT线程中,则很可能数据库查询操作完全正常执行完,但是界面卡死,或者界面得等到所有操作执行完才一下子显示所有查询结果。