当然,必须不要在EDT里执行耗时任务但是现在又有了个疑点public void actionPerformed(ActionEvent e) { new Thread(ABC).start();}这个事件里面的线程ABC 到底也算在EDT线程里面的,还是算EDT之外的独立线程?
始终记住线程是并行运行的。我原来在国外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.这个很好的回答了你的问题。
当然,必须不要在EDT里执行耗时任务但是现在又有了个疑点public void actionPerformed(ActionEvent e)
{
new Thread(ABC).start();}这个事件里面的线程ABC 到底也算在EDT线程里面的,还是算EDT之外的独立线程?
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.这个很好的回答了你的问题。
楼主的问题属于多线程知识的范畴。简单的说,有这样一句话: 可变数据必须在一个线程安全的环境下访问。线程安全的实现手段很多,最简单的一种简化方案就是: 保证数据只在单线程中访问。这就是为什么几乎所有的UI框架都设计为单线程的原因。 这种手段叫做 Thread Confinement(线程约束)。这是因为UI系统本身已经非常复杂,可变数据非常多,如果用通常的加锁等手段对它们分别保护的话,会非常的复杂,——思考一下简化方案的话,就是整个系统所有的可变数据都用同一把锁,然后你就发现,用同一把锁实际上对整个UI系统的访问就是一个虚拟的“单线程”,而且还加上了加锁的内存同步成本,于是更好的方案就显而易见了:干脆用一个专门的线程,——这个线程就是EDT。