其他分享
首页 > 其他分享> > 同步代码块(同步监视器)

同步代码块(同步监视器)

作者:互联网

同步代码块(同步监视器)
  1. 第一种情况:实现接口Runnable方法

    代码块锁synchronized的this指的是同一个demo012;

        package com.Thread;

        public class Demo012 implements Runnable {
            int ticket = 10;

            @Override
            public void run() {
                int ti = 1;
                for (int people = 100; people > 0; people--) {
                    //做一个实时线程监控器;锁定一个代码块;防止多线程争夺一个资源
                    synchronized (this) {//这个this指调用他的对象demo012
                        if (ticket > 0) {
                            System.out.println("我抢到了第" + ticket-- + "张票;从" + Thread.currentThread().getName() + "窗口");
                        }
                    }
                }
            }
        }
        package com.Thread;
        public class Demo011 {
            public static void main(String[] args) {
                Demo012 demo012 = new Demo012();
                Thread thread = new Thread(demo012,"1号");
                thread.start();
                Thread thread2 = new Thread(demo012,"2号");
                thread2.start();
                Thread thread3 = new Thread(demo012,"3号");
                thread3.start();
            }
        }
  1. 第二种情况:继承方法Thread方法

    这里,我们用到字节码文件来锁定监视对应的线程

        package com.Thread;

        public class TrainTicket extends Thread{
            static int trainticket =10;
            public TrainTicket(String name) {
                super(name);
            }
            public void run() {
                //做一个线程同步监视器;this一个代码块有3个对象;这里TrainTicket的字节码唯一性
                synchronized(TrainTicket.class){
                    for(int i = 1;i<=100;i++){//有100人在抢票
                        if(trainticket>0){
                            System.out.println("我抢到了火车票;第"+trainticket--+"张;从"+this.getName()+"窗口");
                        }
                    }
                }
            }
        }
        package com.Thread;
        public class Demo001 {
            public static void main(String[] args) {
                TrainTicket trainTicket1 = new TrainTicket("1号");
                trainTicket1.start();
                TrainTicket trainTicket2 = new TrainTicket("2号");
                trainTicket2.start();
                TrainTicket trainTicket3 = new TrainTicket("3号");
                trainTicket3.start();
            }
        }

标签:同步,Thread,demo012,代码,start,监视器,new,TrainTicket,public
来源: https://www.cnblogs.com/188221creat/p/16165696.html