码迷,mamicode.com
首页 > 编程语言 > 详细

多线程之同步代码块

时间:2015-03-04 06:25:12      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:private   public   多线程   

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

         }

}


多线程之同步代码块

标签:private   public   多线程   

原文地址:http://9882931.blog.51cto.com/9872931/1616981

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!