Java: Swing Libraries & Thread Safety

后端 未结 11 2266
后悔当初
后悔当初 2020-11-28 05:27

I\'ve often heard criticism of the lack of thread safety in the Swing libraries. Yet, I am not sure as to what I would be doing in my own code with could cause issues:

11条回答
  •  攒了一身酷
    2020-11-28 05:56

    It's not just that Swing is not thread-safe (not much is), but it's thread-hostile. If you start doing Swing stuff on a single thread (other than the EDT), then when in cases where Swing switches to the EDT (not documented) there may well be thread-safety issues. Even Swing text which aims to be thread-safe, isn't usefully thread-safe (for instance, to append to a document you first need to find the length, which might change before the insert).

    So, do all Swing manipulations on the EDT. Note the EDT is not the thread the main is called on, so start your (simple) Swing applications like this boilerplate:

    class MyApp {
        public static void main(String[] args) {
            java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
                runEDT();
            }});
        }
        private static void runEDT() {
            assert java.awt.EventQueue.isDispatchThread();
            ...
    

提交回复
热议问题