多线程购买车票

来源:互联网 发布:风控模型算法 编辑:程序博客网 时间:2024/06/11 18:45
public class Thread1 extends Thread{String name;Thread1(String name){this.name = name;}public void run(){for(int i=0;i<5;i++){System.out.println("Thread线程:"+name);}}}
public class Runnable1 implements Runnable{//String name;////Runnable1(String name){////this.name = name;////}//public void run(){int i;int j=20;for(i=1;i<=5;i++){for(;j>=0;j--){System.out.println(Thread.currentThread().getName()+" "+"余票"+j);}}////for(j=20;j>0;j--){////i++;//if(i<=5){//System.out.println("Runnable线程:"+" "+"窗口"+i+" "+"余票"+j);//}//}//}}


class ThreadDemo extends Thread {   private Thread t;   private String threadName;      ThreadDemo( String name) {      threadName = name;     }      public void run() {      System.out.println("Running " +  threadName );      try {         for(int i = 4; i > 0; i--) {            System.out.println("Thread: " + threadName + ", " + i);            // 让线程睡醒一会            Thread.sleep(50);         }      }catch (InterruptedException e) {         System.out.println("Thread " +  threadName + " interrupted.");      }      System.out.println("Thread " +  threadName + " exiting.");   }      public void start () {      System.out.println("Starting " +  threadName );      if (t == null) {         t = new Thread (this, threadName);         t.start ();      }   }} public class TestTickets {    public static void main(String args[]) {      ThreadDemo T1 = new ThreadDemo( "Thread-1");      T1.start();            ThreadDemo T2 = new ThreadDemo( "Thread-2");      T2.start();   }   }//class SaleTicket1 implements Runnable{// int tickets = 20;// public void run(){// //   while(tickets > 0){ //   //   System.out.println(Thread.currentThread().getName() + "卖出 第 "+ (20 - tickets + 1)+"张票");//   tickets--;//   }//   }//   try{//   Thread.sleep(500);//   }catch(InterruptedException e){//    e.printStackTrace();//   }// } //   ////   sale();////   }//////// private synchronized void sale(){////  if(tickets > 0){////   System.out.println(Thread.currentThread().getName() + "卖出 第 "+ (20 - tickets + 1)+"张票");////   tickets--;////   try{////    Thread.sleep(500);////   }catch(InterruptedException e){////    e.printStackTrace();////   }////  }//// }////}//public class TestTickets {//  //public static void main(String[] args){////SaleTicket1 st = new SaleTicket1();//Thread t1 = new Thread(st, "一号窗口");//Thread t2 = new Thread(st, "二号窗口");//Thread t3 = new Thread(st, "三号窗口");//Thread t4 = new Thread(st,"四号窗口 ");//t1.start();//t2.start();//t3.start();//t4.start();//  // //  // }//}


原创粉丝点击