多线程——DelayQueue(带有延迟时间的无界Queue)控制网吧网民下机

DelayQueue:带有延迟时间的Queue
其中的元素只有当其指定的延迟时间到了,才能够从队列中获取到该元素。
DelayQueue中的元素必须实现Delayed接口,DelayQueue是一个没有大小
限制的队列,应用场景很多,比如对缓存超时的数据进行移除、 任务超时
处理、空闲连接的关闭等等

代母逻辑:WangBa (网吧实现Runnable),其中网吧里面有

private DelayQueue delayQeueu = new DelayQueue();

网民实现Delayed,重写方法。

getDelay(TimeUnit unit)判断是否下机,
compareTo(Delayed delayed)判断谁先下机
package com.bfxy.thread.core.collection;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class WangMin implements Delayed {

	private String id;
	
	private String name;
	
	private long endTime;	//上网的截止时间
	
	private final TimeUnit timeUnit = TimeUnit.SECONDS;
	
	public WangMin() {
	}

	public WangMin(String id, String name, long endTime) {
		this.id = id;
		this.name = name;
		this.endTime = endTime;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	// 用来判断是否到了下机时间
	@Override
	public long getDelay(TimeUnit unit) {
		return endTime - System.currentTimeMillis();
	}
	
	@Override
	public int compareTo(Delayed delayed) {
		WangMin w = (WangMin)delayed;
		return this.getDelay(timeUnit) - w.getDelay(timeUnit) > 0 ? 1 : -1;
	}

}

package com.bfxy.thread.core.collection;

import java.util.concurrent.DelayQueue;

public class WangBa implements Runnable {

	private DelayQueue delayQeueu = new DelayQueue();
	
	public boolean start = true;	//表示网吧营业
	
	public void startMachine(String id, String name, int money) {
		WangMin wm = new WangMin(id, name, System.currentTimeMillis() + money * 1000);
		System.err.println("网名: " + name + ", 身份证: " + id + ", 缴费: " + money + "元, 开始上网!" );
		delayQeueu.add(wm);
	}
	
	public void overMachine(WangMin wm) {
		System.err.println("网名: " + wm.getName() + ", 身份证: " + wm.getId() + ", 已经到了下机时间!");
	}
	
	
	@Override
	public void run() {
		while(start) {
			try {
				WangMin wm = delayQeueu.take();
				overMachine(wm);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		
		
		WangBa wangb = new WangBa();
		System.err.println("网吧正常营业: ");
		Thread yingye = new Thread(wangb);
		yingye.start();
		
		wangb.startMachine("001", "张三", 2);
		wangb.startMachine("001", "李四", 5);
		wangb.startMachine("001", "王五", 10);
		
	}
	

}

 建立网吧营业后,运行网吧线程,然后网民来上网,指定时间后自动退出

你可能感兴趣的:(Thread,DelayQueue)