线程同步的例子:汪汪队立大功

队长分配任务给某只狗狗之后就进入等待状态,该狗狗完成任务之后会唤醒他,他就接着分配下一个任务。

public class PAW_Patrol {

    private static Lock lock = new ReentrantLock();
    private static Condition c1 = lock.newCondition();
    private static List<String> tasks = Stream.of("救火", "救溺", "导航", "修理", "找失", "搜救").collect(Collectors.toList());
    private static List<String> members = Stream.of("阿奇", "毛毛", "天天", "灰灰", "小砾", "路马").collect(Collectors.toList());
    private static String task = "";

   
    public static void main(String[] args) {
        Thread ryder = new Thread(new Boy(), "莱德");
        ryder.start();
        for (String dog : members) {
            Thread d = new Thread(new Dog(), dog);
            d.start();
        }
    }
    /**
     * 队长
     */
    private static class Boy implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + ":汪汪队要出动喽!");
            System.out.println(Thread.currentThread().getName() + ":只要你遇到麻烦,就大声呼救!");
            while (!tasks.isEmpty()) {
                try {
                    lock.lock();
                    task = tasks.get(0);
                    System.out.println(Thread.currentThread().getName() + ":收到一个任务:" + task);
                    tasks = tasks.subList(1, tasks.size());
                    Thread.sleep(3000);
                    c1.await();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
            System.out.println(Thread.currentThread().getName() + ":没有困难的工作,只有勇敢的狗狗!");
        }
    }
    /**
     * 狗狗
     */
    private static class Dog implements Runnable {
        @Override
        public void run() {
            while (true) {
                if (!task.equals("")) {
                    try {
                        lock.lock();
                        if ("".equals(task)) {
                            continue;
                        }
                        System.out.println(Thread.currentThread().getName() + ":我来执行" + task + "任务");
                        System.out.println(Thread.currentThread().getName() + ":" + task + "任务执行完毕");
                        task = "";
                        c1.signal();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        lock.unlock();
                    }
                    break;
                } else {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值