Java多线程-卖票示例

方法一:继承Thread类(不使用同步代码块)

TicketDemo_Thread.java

class Ticket extends Thread {

   private static int num = 100;
   String name;

   Ticket(String name) {
      super(name);
   }

   public void run() {
      sale();
   }

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

class TicketDemo_Thread {
   public static void main(String[] args) {
      Ticket t1 = new Ticket("窗口1");
      Ticket t2 = new Ticket("窗口2");
      Ticket t3 = new Ticket("窗口3");
      Ticket t4 = new Ticket("窗口4");
      t1.start();
      t2.start();
      t3.start();
      t4.start();
   }
}

运行结果:

 

方法二:实现Runnable接口。(使用同步代码块)

TicketDemo_Runnable.java

class Ticket implements Runnable {
   private int num = 1000;
   String name;
   public void run() {
      sale();
   }

   private void sale() {

      synchronized (Ticket.class) {
        while (num > 0) {
           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");
      Thread t3 = new Thread(t, "窗口3");
      Thread t4 = new Thread(t, "窗口4");
      t1.start();
      t2.start();
      t3.start();
      t4.start();
   }
}