A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

package cn.itcast4;
/*
* 定义线程执行目标类
*/
public class Tickets implements Runnable{

        //定义成员变量number用来记录票数,供多个线程共享使用
        static int number = 100;
        //定义一个变量,记录奇偶状态
        int x = 0;
        //定义卖票逻辑
        public void run() {
                while(true) {
                        if(x%2==0) {
                                //使用同步代码块,将需要同步的代码包裹
//                                非静态方法的锁为对象this
                                synchronized (this) {
//                                静态方法的锁为其所在类类本身
//                                synchronized (Tickets.class) {
                                        //如果票数是正的,说明有票,就卖票
                                        if(number>0) {
                                                //每卖一张票就将票数减1
                                                System.out.println(Thread.currentThread().getName()+"正在销售第"+ number +"号票");
                                                number--;
                                        }
                                }
                        }else {
                                method();
                        }
                        x++;
                }
        }
//        //同步方法:在方法上加同步
//        public synchronized void method() {
//                //使用同步代码块,将需要同步的代码包裹
//                        try {
//                                Thread.sleep(10);
//                        } catch (InterruptedException e) {
//                                e.printStackTrace();
//                        }
//                       
//                        //如果票数是正的,说明有票,就卖票
//                        if(number>0) {
//                                //每卖一张票就将票数减1
//                                System.out.println(Thread.currentThread().getName()+"正在销售第"+ number +"号票");
//                                number--;
//                        }
//        }
       
        public static synchronized void method() {
                //使用同步代码块,将需要同步的代码包裹
//                synchronized (lock) {
                        try {
                                Thread.sleep(10);
                        } catch (InterruptedException e) {
                                e.printStackTrace();
                        }
                       
                        //如果票数是正的,说明有票,就卖票
                        if(number>0) {
                                //每卖一张票就将票数减1
                                System.out.println(Thread.currentThread().getName()+"正在销售第"+ number +"号票");
                                number--;
                        }
//                }
        }

}


您需要登录后才可以回帖 登录 | 加入黑马