SwingUtilities.InvokeLater

 
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class Swinguti extends Thread{
   final Runnable doHelloWorld;
   int x=1,y=2;
   int res=0;
   public Swinguti()
  {
    doHelloWorld = new Runnable(){
       public void run()
      {
         try {
           //休眠1s
          Thread.sleep(1000);
          System.out.println( "休眠完成...");
          x=100;
        } catch (InterruptedException e) {
           // TODO Auto-generated catch block
          e.printStackTrace();
        }
        System.out.println( "Hello World on"+Thread.currentThread());
      }
    };
  }
   public void run()
  {
     try
    {
       /*invokeAndWait(Runnable doRun)    
                                                    导致 doRun.run() 在 AWT 事件指派线程上同步执行*/
       /*invokeLater(Runnable doRun)    
                     导致 doRun.run() 在 AWT 事件指派线程上异步执行。*/
        
      SwingUtilities.invokeAndWait(doHelloWorld);
       //等待线程doHelloWorld结束,x的值被doHelloWorld线程改为100,然后再
       //进行当前线程的操作z=x+y,结果为102,如图a
        
       //SwingUtilities.invokeLater(doHelloWorld);//当前线程与doHelloWorld异步执行
//      而不会去等待doHelloWorld,故x的值还没来得及改变,已经执行了res=x+y,故结果为3,如图b
        
      res=x+y;
    }
     catch(Exception e)
    {
      e.printStackTrace();
    }
    System.out.println(res);
    System.out.println( "Finished on"+Thread.currentThread());
  }
   public static void main(String args[])
  {
    Swinguti sg= new Swinguti();
    sg.start();
  }
}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

 
 

你可能感兴趣的:(java,职场,休闲)