class MyThreadimplements Runnable{

         private int ticket = 6;

         @Override

         public void run(){

                   for(int i = 0;i < 10;i++){

                            synchronized(this){  //同步代码块

                                     if(this.ticket>0){

                                               try{

                                                        Thread.sleep(1000);  //线程休眠

                                               }catch (InterruptedException e) {

                                                        e.printStackTrace();

                                               }

                                               System.out.println(Thread.currentThread().getName()

                                                                 +"卖票,ticket = "+this.ticket--);

                                     }

                            }

                   }

         }

}

public classTestDemo {

         public static void main(String[] args){

                   MyThread mt = new MyThread();

                   new Thread(mt,"线程A").start(); //线程命名

                   new Thread(mt,"线程B").start();

                   new Thread(mt,"线程C").start();

                   new Thread(mt,"线程D").start();

                   new Thread(mt,"线程E").start();

         }

}

同步方法:

class MyThread2implements Runnable{

         private int ticket = 6;

         @Override

         public void run(){

                   for(int i = 0;i < 10;i++){

                            this.sale();

                   }

         }

        

         public synchronized void sale(){

                   if(this.ticket > 0){

                            try {

                                     Thread.sleep(100);

                            } catch(InterruptedException e) {

                                     e.printStackTrace();

                            }

                            System.out.println(Thread.currentThread().getName()+"卖票,ticket = "+this.ticket);

                            ticket--;

                   }

         }

}

public classTestDemo2 {

         public static void main(String[] args){

                   MyThread2 mt = newMyThread2();

                   new Thread(mt,"票贩子A").start();

                   new Thread(mt,"票贩子B").start();

                   new Thread(mt,"票贩子C").start();

                   new Thread(mt,"票贩子D").start();

                   new Thread(mt,"票贩子E").start();

         }

}