Java: Swing Libraries & Thread Safety

后端 未结 11 2295
后悔当初
后悔当初 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:58

    Here's a pattern for makng swing thread-freindly.

    Sublass Action (MyAction) and make it's doAction threaded. Make the constructor take a String NAME.

    Give it an abstract actionImpl() method.

    Let it look like.. (pseudocode warning!)

    doAction(){
    new Thread(){
       public void run(){
        //kick off thread to do actionImpl().
           actionImpl();
           MyAction.this.interrupt();
       }.start();  // use a worker pool if you care about garbage.
    try {
    sleep(300);
    Go to a busy cursor
    sleep(600);
    Show a busy dialog(Name) // name comes in handy here
    } catch( interrupted exception){
      show normal cursor
    }
    

    You can record the time taken for the task, and next time, your dialog can show a decent estimate.

    If you want to be really nice, do the sleeping in another worker thread too.

提交回复
热议问题