多线程同步程序

package Bean;


public class ThreadTest {
 
 public static void main(String[] args){
  
  //int i = 200;
  Thread2 trd2 = new Thread2();
  
  //trd2.setDaemon(true);
  try{
  new Thread(trd2).start();
  Thread.sleep(1);
  trd2.str = new String("method");
  new Thread(trd2).start();
  //new Thread(trd2).start();
  }
  catch(Exception e){
   System.out.println(e.getMessage());
  }
  
  /*while(true)
  {
  System.out.println("main"+Thread.currentThread().getName());
  }*/
  
 }

}

class Print{
 
 public void printRun(int saleNum)
 {
  if(saleNum > 0)
   System.out.println("Print run!" + saleNum);
 }
}

class Thread2 implements Runnable// extends Thread
{
 int saleNum = 100;
 
 Print pt = new Print();
 String str = new String("");
 public void run()
 {

   if(str.equals("method"))
   {
    while(true)
    {
    sale();
    }    
   }
   else
   {

    while(true)
     {
      synchronized(this)
      {
      if(saleNum > 0)
      {
       //System.out.println("Print run!" + saleNum--);
       try {
        Thread.sleep(10);
       } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
       //pt.printRun(saleNum--);
       System.out.println(Thread.currentThread().getName()+" is saling"+ saleNum--);
      }
     }
    }
  }

 }
  
  public synchronized void sale()
  {

    
     if(saleNum > 0)
     {
      //System.out.println("Print run!" + saleNum--);
      try {
       Thread.sleep(10);
      } catch (InterruptedException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      //pt.printRun(saleNum--);
      System.out.println(Thread.currentThread().getName()+" is saling method"+ saleNum--);
     }
  }
 
 
}
 

你可能感兴趣的:(多线程,thread,bean)