比如说我的程序有两个线程A和B,加上JVM的主线程,一共是三个线程,现在我要B线程在A线程结束后才启动,而主线程则不受影响,一直运行,该如何做?

解决方案 »

  1.   

    public class Threads
    {
    public static void main(String args[])
    {
    A a = new A();
    B b = new B(a);
        a.start();

        
            b.start();
            
      }
      }
    class A extends Thread
    {
       boolean cork = true;
    public void run()
    {
    for(int x = 1;x <=10;x++)
    {
       System.out.println("线程A:" + x);
       try{Thread.sleep(50);}catch(Exception e){}
       }
       setCork();
       try{notifyAll();}catch(Exception e){}
       }
       
       public boolean getCork()
       {
        return cork;
       }
       public void setCork()
       {
        cork = false;
       }
       }
       
    class B extends Thread
    {
       A a;
       public B(A a)
       {
            this.a = a;
       }
       public void run()
    {
       System.out.println("B等待A执行完完毕中......");
       while(a.getCork())
           {
             
             try{this.wait();}catch(Exception e){}
             
            }
            System.out.println("B开始执行中......");
    for(int x = 1;x <=10;x++)
    {
      
      
       System.out.println("线程B:" + x);
       try{Thread.sleep(50);
          
          }catch(Exception e){}
       }
       }
       }
      

  2.   

    b.join()
    a.start();
    如果主线程不等待的话.就再起个c线程,在c线程内
    public void run(){
    b.join();
    直到b线程运行结束,再运行下一步!
    a.start();
    }