synchronized与ReentrantLock实现共享资源的消费

2018-08-17 09:40:54来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

主方法

public class synchronizedTest {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();  
        TicketSystem ticketSystem=new TicketSystem();
        Thread  t1=new Thread(ticketSystem);
        Thread  t2=new Thread(ticketSystem);
        Thread  t3=new Thread(ticketSystem);
        Thread  t4=new Thread(ticketSystem);
        t1.setName("1号售票点");
        t2.setName("2号售票点");
        t3.setName("3号售票点");
        t4.setName("4号售票点");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        while (true) {
            if(ticketSystem.getTicKetNumber()<=0){
                long endTime = System.currentTimeMillis();  
                float seconds = (endTime - startTime) / 1000F;  
                System.out.println(Float.toString(seconds) + " seconds."); 
                break;
            }
        }
    }
}

synchronized线程方法1:

public class TicketSystem implements Runnable {

    private static volatile int ticketNumber = 900;


    public int getTicKetNumber() {
        return this.ticketNumber;
    }

    @Override
    public synchronized  void run() {
        while (true) {
            if (ticketNumber <= 0) {
                break;
            } else {
                System.out.println(Thread.currentThread().getName() + "卖了最后第" + ticketNumber + "票");
                ticketNumber--;
            }
        }
    }

}

ReentrantLock线程方法2:

public class TicketSystem implements Runnable {

    private static volatile int ticketNumber = 900;

    private ReentrantLock lock = new ReentrantLock();

    public int getTicKetNumber() {
        return this.ticketNumber;
    }

    @Override
    public void run() {
        while (true) {
            lock.lock();
            if (ticketNumber <= 0) {
                break;
            } else {
                System.out.println(Thread.currentThread().getName() + "卖了最后第" + ticketNumber + "票");
                ticketNumber--;
            }
            lock.unlock();
        }
    }

}

总结:

synchronized在这里将run()方法加入了锁,其他线程方法时如果当前锁没有释放进去等待状态等线程释放锁后进入锁的争夺。每次只允许一个线程访问。

ReentrantLock 利用lock.lock()获得锁,lock.unlock()释放锁,实现与synchronized同样的效果。

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:java环境变量

下一篇:java高并发思考总结