代码改变世界

每日一练

2012-04-21 23:13  Lves Li  阅读(126)  评论(0编辑  收藏  举报

//多线程小程序  复习

class Ticket implements Runnable
{
 Object obj=new Object();
 Boolean flag=true;
 private int  tick=100;
 public void run()
 {
  if (flag)
  {
  
  while (true)
  {synchronized(this)
   { if (tick>0)
    {
     try
     {
      Thread.sleep(10);
     }
     catch (Exception e)
     {
     }
     System.out.println(Thread.currentThread().getName()+"`````cold ``"+tick--);
    }
   }
  }
  }
  else
  {while(true)
   show();
  }

 }
 public synchronized void  show()
 {
  if (tick>0)
  {
  
  try
  {
   Thread.sleep(10);
  }
  catch (Exception e)
  {
  }
System.out.println(Thread.currentThread().getName()+"`````show``` ``"+tick--);
 }
 }

public class TicketDemo
{public static void main(String args[])
 {
 Ticket t=new Ticket();
 Thread t1=new Thread(t);
 Thread t2=new Thread(t);
 
 t1.start();
 try
 {
  Thread.sleep(10);
 }
 catch (Exception e)
 {
 }
 t.flag=false;
 t2.start();
 //Thread t3=new Thread(t);
 //Thread t4=new Thread(t);
 //t3.start();
 //t4.start();
 }
}