main 线程与子线程同步运行

//先主线程循环10次后子线程循环5次  再主线程循环10次  子线程循环5次
package com.wuxifu.com;

import java.util.Stack;

public class Thread001
{
    public static String  LOCAK="LOCK";//主线程与子线程的锁
   public static void main(String[] args)
{
       MyThread myThread = new MyThread(LOCAK);
       new Thread(myThread).start();
    for (int j = 0; j <2; j++){
      synchronized (LOCAK)
    {
        
     for (int i = 0; i <10; i++)
         System.out.println("main");
 
     try
    {     LOCAK.notify();//先notify再wait
        LOCAK.wait();
    } catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    }  
    }  
}

  
  
  
 
}
class MyThread  implements  Runnable
{
   
    private String LOCAK;
    public MyThread(String  lock)
    {
        this.LOCAK=lock;
    }
     @Override
     public void run()
     {
         for (int j = 0; j <2; j++)
         {
           synchronized (LOCAK)
          {
             
           for (int i = 0; i <5; i++)
             System.out.println("111");
          
           LOCAK.notify();//先notify再wait
               try
               {
                   LOCAK.wait();
               } catch (InterruptedException e)
               {
               }
    
          } 
     }       
 }
   

   
}

猜你喜欢

转载自wuxifu001.iteye.com/blog/1774694