售票的線程方式一(thread):this
1 class SaleTickets extends Thread { 2 static int num = 50; // 總票數 共享的數據,三個窗口同時操做同一份數據 3 //static Object o = new Object(); 4 public SaleTickets (String name) { 5 super(name); 6 } 7 // 重寫run方法:賣票的任務 8 public void run() { 9 10 while (true) { 11 synchronized ("hh") { //任意類型的對象,鎖對象應該是同一個對象 12 try { 13 Thread.sleep(500); 14 } catch (InterruptedException e) { 15 // TODO: handle exception 16 e.printStackTrace(); 17 } 18 if(num > 0) { 19 System.out.println(this.getName() + "賣了第" + num + "票"); 20 num--; 21 22 } else { 23 System.out.println("票已售完"); 24 break; 25 } 26 } 27 28 29 } 30 } 31 32 } 33 public class Demo4 { 34 35 /** 36 * @param args 37 */ 38 public static void main(String[] args) { 39 // TODO Auto-generated method stub 40 SaleTickets t1 = new SaleTickets("窗口1"); 41 SaleTickets t2 = new SaleTickets("窗口2"); 42 SaleTickets t3 = new SaleTickets("窗口3"); 43 t1.start(); 44 t2.start(); 45 t3.start(); 46 } 47 48 }
售票的線程方式二(Runnable):spa
1 class SaleTickets1 implements Runnable { 2 static int num = 50; 3 public void run() { 4 while (true) { 5 synchronized ("djj") { 6 if (num > 0) { 7 System.out.println(Thread.currentThread().getName() + "賣出第" + num + "張票"); 8 num--; 9 } else { 10 System.out.println("票已售盡"); 11 break; 12 } 13 } 14 15 } 16 17 } 18 } 19 public class Demo8 { 20 21 /** 22 * @param args 23 */ 24 public static void main(String[] args) { 25 // TODO Auto-generated method stub 26 //建立實現類對象 27 SaleTickets1 st = new SaleTickets1(); 28 // 建立三個線程對象 29 Thread t = new Thread(st, "窗口1"); 30 Thread t1 = new Thread(st, "窗口2"); 31 Thread t2 = new Thread(st, "窗口3"); 32 t.start(); 33 t1.start(); 34 t2.start(); 35 } 36 37 }