多线程之同步代码块

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();

         }

}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。