阻塞队列,用于生产者消费者模式
static BlockingQueue<String> queue = new ArrayBlockingQueue<>(10);//循环式队列
static BlockingQueue<String> queue2 = new LinkedBlockingDeque<>();//基本上是无上限的
static BlockingQueue<String> queue3 = new PriorityBlockingQueue<>();//优先级阻塞队列
消费者计算斐波那契数,生产者输入数字
package package1218;
import java.util.Scanner;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueDemo {
static BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);//循环式队列
private static long fib(int n){
if (n < 2){
return n;
}
return fib(n - 1) + fib(n - 2);
}
private static class Customer extends Thread{
@Override
public void run() {
while (true){
try {
int n = queue.take();
long result = fib(n);
System.out.printf("fib(%d) = %d\n",n,result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
Customer customer = new Customer();
customer.start();
}
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("请输入n");
int n = scanner.nextInt();
queue.put(n);
}
}
}
定时器
规定5秒钟后执行某段代码
public class MyTimer {
public static void main(String[] args) {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
//时间到了要去执行的代码
System.out.println("五秒钟到了");
}
};
timer.schedule(task,5000);
}
}
自己实现
public class MyTimer {
private static class MyTimerTask implements Comparable<MyTimerTask> {
long runATime;
Runnable target;
public MyTimerTask(long delay, Runnable target) {
this.runATime = System.currentTimeMillis() + delay;
this.target = target;
}
@Override
public int compareTo(MyTimerTask o) {
if (runATime < o.runATime){
return -1;
}else if (runATime == o.runATime){
return 0;
}else {
return 1;
}
}
}
private PriorityBlockingQueue<MyTimerTask> queue = new PriorityBlockingQueue<>();
Thread worker = new Worker();
private class Worker extends Thread{
@Override
public void run() {
while (true){
try {
MyTimerTask task = queue.take();
if (task.runATime <= System.currentTimeMillis()){
task.target.run();
}else {
//没到时间
queue.put(task);
Thread.sleep(task.runATime - System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
MyTimer(){
worker.start();
}
public void schedule(Runnable target,long delay){
MyTimerTask task = new MyTimerTask(delay,target);
queue.put(task);
}
public static void main(String[] args) {
Runnable targer = new Runnable() {
@Override
public void run() {
System.out.println("五秒钟");
}
};
MyTimer timer = new MyTimer();
timer.schedule(targer,5000);
}
}
注意一下,util包的timer(timeTask,delay)
传入的是timerTask对象
我自己实现的MyTimer(target,delay)
target是Runnable对象.
本文介绍了阻塞队列在生产者消费者模式中的使用,消费者计算斐波那契数,而生产者负责输入数字。同时,文章探讨了定时器的设定,包括使用util包中的Timer以及自行实现的MyTimer,强调了如何在指定延迟后执行特定代码,其中传入的对象分别为TimerTask和Runnable。
545

被折叠的 条评论
为什么被折叠?



