class TicketThread implements Runnable{
       int tickets=100;
       public void run(){
             while(true){   
                  synchronized(this){         
                      if(tickets>0){   
                           try{
                                Thread.sleep(100);
                            } catch(Exception e){
                                 e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName()+":"+tickets--); 
                       }
                  }
             }
       }
}

public class Solution{
     public static void main(String[] args){
         TicketThread  tt=new TicketThread();
         new Thread(tt,"Thread 1").start();
         new Thread(tt,"Thread 2").start();
         new Thread(tt,"Thread 3").start();
         new Thread(tt,"Thread 4").start();
     }
}

实现线程间交替卖票(实际上也是两个线程交替打印奇偶数)

class TicketThread implements Runnable{
       int tickets=100;
       public void run(){
             while(true){   
                  synchronized(this){         
                      if(tickets>0){   
                           notify();
                           try{
                                Thread.sleep(100);
                            } catch(Exception e){
                                 e.printStackTrace();
                            }
                            System.out.println(Thread.currentThread().getName()+":"+tickets--); 
                            try{
                                wait();
                            }catch(InterruptedException e){
                                e.printStackTrace();
                            }
                       }
                  }
             }
       }
}

public class Solution{
     public static void main(String[] args){
         TicketThread  tt=new TicketThread();
         new Thread(tt,"Thread 1").start();
         new Thread(tt,"Thread 2").start();
         //new Thread(tt,"Thread 3").start();
         //new Thread(tt,"Thread 4").start();
     }
}

 

 posted on 2018-12-24 22:31  会飞的金鱼  阅读(126)  评论(0)    收藏  举报