运行下面的代码你会发现:先输出k的循环,然后j、i的循环相间输出
有没有办法先输出k的循环,然后输出j的循环,再输出i的循环?
而且是不修改MyThread的代码public class JoinThread
{
    public static void main(String[] args)
    {
        
        MyThread myThread = new MyThread();
        myThread.start();
        try
        {
            myThread.join();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        for(int i = 0; i < 100; i++)
        {
            System.out.println("i = " + i);
        }
    }
    
    private static class MyThread extends Thread
    {
        public void run()
        {
            for(int k = 0; k < 100; k++)
            {
                System.out.println("k = " + k);
            }
            
            Thread thread = new Thread()
            {
                public void run()
                {
                    for(int j = 0; j < 100; j++)
                    {
                        System.out.println("j = " + j);
                    }
                }
            };
            thread.start();
        }
    }
}

解决方案 »

  1.   

    在 thread.start(); 
    下面加上 thread.join();让外层的run等待内部的线程运行完再退出.
      

  2.   

    public class JoinThread 

        public static void main(String[] args) 
        { 
            
            MyThread myThread = new MyThread(); 
            myThread.start(); 
            try 
            { 
                myThread.join(); 
            } 
            catch(Exception ex) 
            { 
                ex.printStackTrace(); 
            } 
            for(int i = 0; i < 5; i++) 
            { 
                System.out.println("i = " + i); 
            } 
        } 
        
        private static class MyThread extends Thread 
        { 
            public void run() 
            { 
                for(int k = 0; k < 5; k++) 
                { 
                    System.out.println("k = " + k); 
                } 
                
                Thread thread = new Thread() 
                { 
                    public void run() 
                    { 
                        for(int j = 0; j < 5; j++) 
                        { 
                            System.out.println("j = " + j); 
                        } 
                    } 
                }; 
                thread.start(); 
                try{
                thread.join();
                }catch(InterruptedException e){}
            } 
        } 
    }