Java多线程-验证静态同步函数的锁

静态函数使用的锁是 :该函数所属的字节码文件对象。

可以用getClass()获取,也可以用当前  类名.class


class Ticket implements Runnable {

   private static int num = 200;
   boolean flag = true;
   String name;

   public void run() {
      if (flag) {
        synchronized (this.getClass())// (Ticket.class)

        {
           while (num > 0) {
              try {
                 Thread.sleep(10);
              } catch (Exception e) {}
              System.out.println(Thread.currentThread().getName() + ":票号" + (num--));
           }
        }
      } else
        sale();
   }

   private static synchronized void sale() {
      while (num > 0) {
        try {
           Thread.sleep(10);
    } catch (Exception e) {}
        System.out.println(Thread.currentThread().getName() + ":票号"+ (num--));
      }
   }
}

class TicketDemo_Runnable {

   public static void main(String[] args) {
      Ticket t = new Ticket();
      Thread t1 = new Thread(t, "窗口1");
      Thread t2 = new Thread(t, "窗口2");
      t1.start();
      try {
        Thread.sleep(10);
    } catch (Exception e) {}
      t.flag = false;
      t2.start();
   }
}