多线程同步 安全性

来源:互联网 发布:深圳交通中心 知乎 编辑:程序博客网 时间:2024/06/05 21:12

class ThreadDemo1
{
   public static void main(String [] args)
   {
    
       
      TestThread tt = new TestThread();
      new Thread(tt).start();
      new Thread(tt).start();
      new Thread(tt).start();
      new Thread(tt).start();
       
    }
    
 }

class  TestThread implements Runnable
{
   int tickets = 100;
   String str = new String("");
  public void run()
  {
     while(true)
     {
       synchronized(str)
       {
       if(tickets > 0)
       {
        try{Thread.sleep(10);}catch(Exception e){}
        System.out.println(Thread.currentThread().getName() +"is saling ticket"+ tickets--);
        }
       }
     }a
    }
}

原创粉丝点击