单例模式,阻塞队列,定时器

单例模式

是多线程的一个案例,是一种常见的设计模式。

两种实现单例模式的方法:
1、饿汉模式
2、懒汉模式

在这里插入图片描述
在这里插入图片描述

阻塞队列

是一个先进先出的队列
入队列的时候如果发现队列满了,就会阻塞,直到有其他线程出队列后,才能继续如对类。
出队列时候如果发现队列空了,也会阻塞,直到有其他线程入队列后,才能继续出队列。

public class ThreadDemo3 {
    static class BlockingQueue {
        //基于数组实现
        private int[] array = new int[1000];
        private int head = 0;
        private  int tail = 0;
        private int size = 0;

        public  void put(int value) throws InterruptedException {
            synchronized (this) {
                if (size == array.length) {
                    wait();
                }
                array[tail] = value;
                tail++;
                if (tail == array.length) {
                    tail = 0;
                }
                size++;
                notify();
            }
        }

        public  int take() throws InterruptedException {
            int ret = -1;
            synchronized (this) {
                if (size == 0) {
                    wait();
                }
                 ret = array[head];
                head++;
                if (head == array.length) {
                    head = 0;
                }
                size--;
                notify();
            }
            return ret;
        }
    }

    public static void main(String[] args) {
        BlockingQueue blockingQueue = new BlockingQueue();
        Thread producer = new Thread() {
            @Override
            public void run() {
                for (int i = 0;i<10000;i++) {
                    try {
                        blockingQueue.put(i);
                        System.out.println("生产成功"+i);
                        sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        producer.start();
        Thread consumer = new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        int ret = blockingQueue.take();
                        System.out.println("消费元素"+ret);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        consumer.start();
    }
}

代码中,假如吧notify改为notifyAll,被等待的线程全都被唤醒,这时假如一个线程出队列结束后,队列为空,下个线程再去出队列时,就会发生逻辑错误。这时,只需要把判断数组是否为空,或者是否满的时候,把if字句改为while循环,这时,当多个线程竞争锁,消费者1先获取到锁,队列为空就返回来,再次执行while由于生产者生产了一个元素过来,size不为空,循环推出,消费者1就可以执行后面的出队列操作了,然后释放锁,当消费者2获取到锁后,wait也返回了,再次执行while,由于刚才的元素已经取走了,size还是为0,循环继续执行调用wait,继续等,就不会出现上述的逻辑错误,所以之后优先考虑while。

定时器

好比一个闹钟,有些逻辑,并不想立刻执行,而是需要等一定时间后再来执行。

定时器构成:
1.使用一个Task类来描述“一段逻辑”(一个要执行的任务),同时也要记录这个任务在啥时候来执行。
2.使用一个阻塞优先队列来组织若干个Task。
3.还需要一个扫描线程,扫描线程要循环检测队首元素是否需要执行,如果需要执行,就执行这个任务。

import java.util.concurrent.PriorityBlockingQueue;

class Task implements Comparable<Task>{
    //用runnable中的run方法来描述这个任务是啥
    public Runnable command;
    public long time;

    public Task(Runnable command, long after) {
        this.command = command;
        this.time = System.currentTimeMillis()+after;
        //相对时间,毫秒级别的时间戳
    }
    public void run() {
        command.run();
    }

    @Override
    public int compareTo(Task o) {
        return (int)(this.time-o.time);
    }
}
class Worker extends Thread {
    public PriorityBlockingQueue<Task> queue = null;

    public Worker( PriorityBlockingQueue<Task> queue) {

        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Task task = queue.take();
                long curTime = System.currentTimeMillis();
                if (task.time>curTime) {
                    queue.put(task);
                }else {
                    task.run();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }

        }
    }
}
class Timer {

    public PriorityBlockingQueue<Task> queue = new PriorityBlockingQueue<>();
    public Timer() {
        Worker worker = new Worker(queue);
        worker.start();
    }
    public void schedule(Runnable command,long after) {
        Task task = new Task(command,after);
        queue.put(task);
    }



}

public class ThreadDemo4 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hehe");
                timer.schedule(this,2000);
            }
        },2000);
    }

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lhj_loveFang_1105

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值