线程安全

同步代码块,同步方法,Lock接口

Object ojb=new Object();

同步代码块:

public void run(){
        while(true){
            synchronized (obj) {
                if(ticket>0){
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()
                            +"窗口卖了第"+ticket--+"张票");
                }
            }
        }    
    }

 

synchronized(obj){aaaaa}

同步方法:

aaa();

public synchronized void aaa(){aaaaaa}

public void run(){
        while(true){
            sale();
        }    
    }
    //同步方法
    public synchronized void sale(){
        //可能发生安全问题的代码放进来
        if(ticket>0){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()
                    +"窗口卖了第"+ticket--+"张票");
        }
    }

 

Lock接口方法:

private Lock lk=new ReentrantLock()  //创建Lock对象

lk.lock();       

aaaaaa;

lk.unlock();

 

private Lock lk=new ReentrantLock();
    //重写run
    public void run(){
        while(true){        
            //获取锁
            lk.lock();
            if(ticket>0){
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()
                        +"窗口卖了第"+ticket--+"张票");
            }
            //释放锁
            lk.unlock();
        }
    }        

 

posted on 2019-10-26 10:38  流光若影  阅读(138)  评论(0编辑  收藏  举报