1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package org.linlinjava.litemall.core.notify;
import javax.sound.midi.Soundbank; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
class Produce implements Runnable{
private final BlockingQueue<Integer> queue;
private int task = 1; public Produce(BlockingQueue queue){ this.queue = queue; }
@Override public void run(){ while(true){ try{ System.out.println("生产了一个task"+task); queue.put(task); task++; System.out.println("当前任务数量为"+ queue.size()); Thread.sleep(1000); }catch (Exception ex){ } }
}}
class Consumer implements Runnable{
private final BlockingQueue<Integer> queue;
private int task; public Consumer(BlockingQueue queue){ this.queue = queue; }
@Override public void run(){ while(true){ try{ int a= queue.take();
System.out.println("消费了一个"+ a); System.out.println("当前任务数量为"+ queue.size()); Thread.sleep(2000); }catch (Exception ex){ } }
}}
class Test{
public static void main(String[] args){ ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(5); Produce prd = new Produce(queue); Consumer con =new Consumer(queue); Thread t1= new Thread(prd); Thread t2 =new Thread(con); t1.start(); t2.start(); } }
|