多線程的應用
阿新 • • 發佈:2017-11-26
oid public boolean name ble col sta urn 名稱
需求描述
1. 三個線程,名稱分別為“張三”、“李四”、“票販子”,共同搶100張火車票。
2. 每個線程搶到一張票後,都必須休眠500毫秒,用來模擬網絡延時。
3. 限“票販子”只能搶一張票。
1 public class TicketOffice implements Runnable { 2 private int count = 100; // 記錄剩余票數 3 private int no = 0; // 記錄買到第幾張票 4 private boolean flag = false; //記錄是否售完 5 public boolean x=false; 6 publicvoid run() { 7 while (true) { 8 sale(); 9 if(count<=0){ 10 break; 11 } 12 } 13 } 14 // 賣票 15 public boolean sale() { 16 if (flag==true) { 17 return false; 18 } 19 // 第一步:設置買到第幾張票和剩余票數20 no++; 21 count--; 22 try { 23 Thread.sleep(500); 24 // 模擬網絡延時 25 } catch (InterruptedException e) { 26 e.printStackTrace(); 27 } 28 // 第二步:顯示信息 29 System.out.println(Thread.currentThread().getName() + "搶到第" + no + "張票," + "剩余" + count + "張票!");30 if(count<=0){ 31 flag=true; 32 return false; 33 } 34 if(Thread.currentThread().getName().equals("票販子")){ 35 Thread.currentThread().stop(); 36 } 37 return true; 38 } 39 } 40 41 public class Test { 42 public static void main(String[] args) { 43 TicketOffice ticket =new TicketOffice(); 44 new Thread(ticket,"張三").start(); 45 new Thread(ticket,"李四").start(); 46 new Thread(ticket,"票販子").start(); 47 } 48 }
1 public class TicketOffice implements Runnable { 2 private int count = 100; // 記錄剩余票數 3 private int no = 0; // 記錄買到第幾張票 4 private boolean flag = false; //記錄是否售完 5 public void run() { 6 while (true) { 7 sale(); 8 if(count<=0){ 9 break; 10 } 11 } 12 } 13 // 賣票 14 public synchronized boolean sale() {//同步 15 if (flag==true) { 16 notify(); 17 return false; 18 } 19 // 第一步:設置買到第幾張票和剩余票數 20 no++; 21 count--; 22 try { 23 Thread.sleep(500); 24 // 模擬網絡延時 25 } catch (InterruptedException e) { 26 e.printStackTrace(); 27 } 28 // 第二步:顯示信息 29 System.out.println(Thread.currentThread().getName() + "搶到第" + no + "張票," + "剩余" + count + "張票!"); 30 if(count<=0){ 31 flag=true; 32 return false; 33 } 34 if(Thread.currentThread().getName().equals("票販子")){ 35 try { 36 this.wait(); 37 } catch (InterruptedException e) { 38 e.printStackTrace(); 39 } 40 } 41 return true; 42 } 43 } 44 45 public class Test { 46 public static void main(String[] args) { 47 TicketOffice ticket =new TicketOffice(); 48 new Thread(ticket,"張三").start(); 49 new Thread(ticket,"李四").start(); 50 new Thread(ticket,"票販子").start(); 51 } 52 }
多線程的應用