银行叫号系统线程安全版

使用synchronized(object)实现线程安全

package com.dwz.concurrency.chapter7;

public class TicketWindowRunnable implements Runnable {
    private int index = 1;
    private final static int MAX = 500;
    private final Object MONITOR = new Object();
    
    @Override
    public void run() {
        while(true) {
            synchronized (MONITOR) {
                if(index > MAX) {
                    break;
                }
                
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread() + " 的号码是:" + (index++));
            }
        }
    }

}

测试代码

package com.dwz.concurrency.chapter7;

public class BankVersion2 {
    public static void main(String[] args) {
        TicketWindowRunnable wr = new TicketWindowRunnable();
        Thread thread1 = new Thread(wr, "柜台一");
        Thread thread2 = new Thread(wr, "柜台二");
        Thread thread3 = new Thread(wr, "柜台三");
        
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

使用synchronized给方法签名加锁实现线程安全

package com.dwz.concurrency.chapter7;

public class SynchronizedRunnable2 implements Runnable {
    private int index = 1;
    private final static int MAX = 500;
    private final Object MONITOR = new Object();
    
    @Override
    public void run() {
        while(true) {
            if(ticket()) {
                break;
            }
        }
    }
    
    private synchronized boolean ticket() {
        if(index > MAX) {
            return true;
        }
        
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread() + " 的号码是:" + (index++));
        return false;
    }
}

使用synchronized(this)实现线程安全

package com.dwz.concurrency.chapter7;

public class SynchronizedRunnable2 implements Runnable {
    private int index = 1;
    private final static int MAX = 500;
    private final Object MONITOR = new Object();
    
    @Override
    public void run() {
        while(true) {
            if(ticket()) {
                break;
            }
        }
    }
    private boolean ticket() {
        synchronized (this) {
            if(index > MAX) {
                return true;
            }
            
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //index++ => index = index + 1
            //1.get field index
            //2.index = index + 1
            //3.put field index
            System.out.println(Thread.currentThread() + " 的号码是:" + (index++));
            return false;
        }
    }
}

使用synchronized加锁的时候尽量减小加锁部分代码的粒度,在保证必要的数据安全前提下减少程序执行时间

posted @ 2019-12-18 08:26  龙宇在天  阅读(248)  评论(0编辑  收藏  举报
//右侧添加目录 //增加页面点击显示24字社会主义核心价值观