java使用线程做一个消息队列,wait,notify
作者:bin使用synchronized字段让部分代码或者方法串行执行
使用wait方法,让当前线程进行等待
使用notify方法通知其它线程,锁将要被释放(要等synchronized代码都执行完才释放)
notify和notifyAll的区别:
前者:随机通知一个线程从等待池,进入锁池
后者:通知所有线程,从等待池,进入锁池,进行争抢锁,如果线程没抢到锁,他还会留在锁池中,除非再调用wait方法
理论上,优先级高的线程会先获得锁
package com.zengbingo.chapter5; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.concurrent.TimeUnit; /** * wait * notify * * */ @SpringBootApplication public class Part8 { public static void main(String[] args) throws Exception{ threadSleep(); } /** * 线程sleep * @throws Exception */ private static void threadSleep() throws Exception{ final EventQueue eventQueue = new EventQueue(); /** * 压入 * wait 让使用当前对象的线程进入阻塞状态 */ new Thread(() -> { for (;;){ eventQueue.offer(new EventQueue.Event()); try { TimeUnit.MILLISECONDS.sleep(500); }catch (Exception e){ } } }, "发放者").start(); /** * 取出 * notify 让使用当前对象的线程推出阻塞状态,如果非阻塞则忽略 */ new Thread(() -> { for (;;){ eventQueue.take(); try { TimeUnit.SECONDS.sleep(5); }catch (Exception e){ } } }, "消费者").start(); } }
其中EventQueue
package com.zengbingo.chapter5; import java.util.LinkedList; /** * 使用synchronized字段让部分代码或者方法串行执行 */ public class EventQueue { private final int max; static class Event{} private final LinkedList eventQueue = new LinkedList<>(); private final static int DEFAULT_MAX_EVENT = 10; public EventQueue(){ this(DEFAULT_MAX_EVENT); } public EventQueue(int max){ this.max = max; } public void offer(Event event){ synchronized (eventQueue){ if (eventQueue.size() >= max) { try { System.out.println("eventQueue队列已满"); eventQueue.wait(); }catch (Exception e){ } } System.out.println("eventQueue加入新任务"); eventQueue.addLast(event); eventQueue.notify(); } } public Event take(){ synchronized (eventQueue){ if (eventQueue.isEmpty()) { try{ System.out.println("eventQueue队列是空的"); eventQueue.wait(); }catch (Exception e){ } } System.out.println("eventQueue处理新任务"); Event event = eventQueue.removeFirst(); eventQueue.notify(); return event; } } }