夜光 带你走进 Java基础编程实战(二十五 线程)

夜光序言:

 

情话躲在风里

喜欢的人藏在梦里

你还在我心里

正文:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockExample {

    private static final ReentrantLock queueLock = new ReentrantLock(); //夜光 可重入锁
    private static final ReentrantReadWriteLock orderLock = new ReentrantReadWriteLock(); //夜光 可重入读写锁
    
    /**
     * 夜光
     * 有家奶茶店,点单有时需要排队 
     * 假设想买奶茶的人如果看到需要排队,就决定不买
     * 又假设奶茶店有老板和多名员工,记单方式比较原始,只有一个订单本
     * 老板负责写新订单,员工不断地查看订单本得到信息来制作奶茶,在老板写新订单时员工不能看订单本
     * 
     * 夜光 这就是一个读写分离的情况~~
     * 
     * 多个员工可同时看订单本,在员工看时老板不能写新订单
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        //buyMilkTea();
        handleOrder(); //需手动关闭
    }
    
    public void tryToBuyMilkTea() throws InterruptedException {
        boolean flag = true;
        while(flag)
        {
            if (queueLock.tryLock()) {
                //queueLock.lock();
                long thinkingTime = (long) (Math.random() * 500);
                Thread.sleep(thinkingTime);
                System.out.println(Thread.currentThread().getName() + ": 来一杯夜光牌珍珠奶茶,不要珍珠");
                flag = false;
                queueLock.unlock(); // 夜光 我们把资源释放掉~~
            } else {
                //System.out.println(Thread.currentThread().getName() + ":" + queueLock.getQueueLength() + "人在排队");
                System.out.println(Thread.currentThread().getName() + ": 再等等");
            }
            if(flag)
            {
                Thread.sleep(1000);
            }
        }
        
    }
    
    public void addOrder() throws InterruptedException {
        orderLock.writeLock().lock();
        long writingTime = (long) (Math.random() * 1000);
        Thread.sleep(writingTime);
        System.out.println("架构师新加一笔订单");
        orderLock.writeLock().unlock();
    }
    
    public void viewOrder() throws InterruptedException {
        orderLock.readLock().lock();
            // 夜光,下面几行代码都可以共享readLock(),不像之前的
        long readingTime = (long) (Math.random() * 500);
        Thread.sleep(readingTime);
        System.out.println(Thread.currentThread().getName() + ": 查看订单本");
        orderLock.readLock().unlock();            

    }
    
    public static void buyMilkTea() throws InterruptedException {
        LockExample lockExample = new LockExample();
        int STUDENTS_CNT = 10;
        
        Thread[] students = new Thread[STUDENTS_CNT];
        
        // 夜光 下面我们完成了student数组的初始化工作~~
        for (int i = 0; i < STUDENTS_CNT; i++) {
            students[i] = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        long walkingTime = (long) (Math.random() * 1000);
                        Thread.sleep(walkingTime);
                        lockExample.tryToBuyMilkTea();
                    } catch(InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                }
                
            }
            );
            
            students[i].start();
        }
        
        for (int i = 0; i < STUDENTS_CNT; i++)
            students[i].join();

    }
    
    
    public static void handleOrder() throws InterruptedException {
        LockExample lockExample = new LockExample();
        
        
        Thread boss = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        lockExample.addOrder();
                        long waitingTime = (long) (Math.random() * 1000);
                        Thread.sleep(waitingTime);
                    } catch (InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        });
        boss.start();

        int workerCnt = 3;
        Thread[] workers = new Thread[workerCnt];
        for (int i = 0; i < workerCnt; i++)
        {
            workers[i] = new Thread(new Runnable() {

                @Override
                public void run() {
                    while (true) {
                        try {
                                lockExample.viewOrder();
                                long workingTime = (long) (Math.random() * 5000);
                                Thread.sleep(workingTime);
                            } catch (InterruptedException e) {
                                System.out.println(e.getMessage());
                            }
                        }
                }
                
            });
            
            workers[i].start();
        }
        
    }
}
 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值