zoukankan      html  css  js  c++  java
  • 线程安全

    同步代码块,同步方法,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();
            }
        }        
  • 相关阅读:
    最小化程序到托盘
    Delphi
    c# 多线程
    下载地址加密
    一个很让我郁闷的java异常
    XmlBeanFactory和ApplicationContext读取spring xml配置文件
    tomcat部署war出错的问题
    JAXB 实现List接口
    Mongo数据模型
    JAXB, Web Services, and Binary Data
  • 原文地址:https://www.cnblogs.com/god3064371/p/11738866.html
Copyright © 2011-2022 走看看