A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

  1. class Ticket implements Runnable//extends Thread
  2. {
  3.         private int tick = 300;
  4.         Object obj = new Object();
  5.         public void run()
  6.         {
  7.                 while (true)
  8.                 {
  9.                         synchronized(obj)
  10.                         {
  11.                                 if(tick>0)
  12.                                 {
  13.                                         try
  14.                                         {       
  15.                                                 Thread.sleep(5);
  16.                                                 System.out.println(Thread.currentThread().getName()+"...sale: "+tick--);
  17.                                         }
  18.                                         catch(Exception e)
  19.                                         {
  20.                                         }
  21.                                 }
  22.                         }
  23.                 }
  24.         }
  25. }
  26. class  ThreadTest3
  27. {
  28.         public static void main(String[] args)
  29.         {
  30.                 Ticket t = new Ticket();//这个不是线程
  31.                 Thread th1 = new Thread(t);
  32.                 Thread th2 = new Thread(t);
  33.                 Thread th3 = new Thread(t);
  34.                 Thread th4 = new Thread(t);
  35.                 th1.start();
  36.                 th2.start();
  37.                 th3.start();
  38.                 th4.start();
  39.         }
  40. }
复制代码
以买票的例子来说,如果把while循环放在synchronized里面,那释放锁的动作要等while循环结束才会做。这样第一个线程开始了,就会直接把票都卖完才会释放锁。

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马