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

同步函数使用的锁是this

同步函数和同步代码块的区别:

同步函数使用的锁是固定的this

同步代码块的锁是任意的。

建议使用同步代码块

class Ticket implements Runnable {
   private int num = 200;
   boolean flag = true;
   String name;

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

   private 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();
   }
}