java队列 notify_java使用线程做一个消息队列,wait,notify

java使用线程做一个消息队列,wait,notify作者:曾 彬

使用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;

}

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值