队列的特点就先进先出,保证在多个线程并发时数据安全性,通过多线程的互斥同步实现,当队列为空时只能入队即只能插入数据,当队列满时只能出队,
下边程序主要模拟场景为:2个线程产生数据,在队列不满的情况下,将数据插入队列,另外2个线程实现取数据(当队列为空时,等待其他线程放入数据),出队,并且队列大小减1,
import java.util.Random;
/*** ***********************************************************
* 通过数组实现队列 队列特性 FIFO
* ***********************************************************
*/
public class ArrayBlockQueue {
public static void main(String[] args) {
HandQueue handQueue = new HandQueue();
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
String data = String.valueOf(System.currentTimeMillis());
handQueue.put(data);
}
}
}).start();
}
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(new Random().nextInt(100));
} catch (InterruptedException e) {
e.printStackTrace();
}
handQueue.take();
}
}
}).start();
}
}
}
class HandQueue {
private String[] data = new String[100];
boolean isFull = false;
boolean isEmpty = true;
int index = 0;
protected synchronized void put(String str) {
while (isFull) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("当前线程为:" + Thread.currentThread().getName() + ",进入队列数为:" + str);
data[index++] = str;
isEmpty = false;
if (index == 99) {
isFull = true;
}
this.notify();
}
protected synchronized void take() {
while (isEmpty) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (data[0] != null) {
System.out.println("当前线程为:" + Thread.currentThread().getName() + "从队列取数:" + data[0]);
for (int i = 0; i < index; i++) {
if (i == 99) {
data[i] = "";
} else {
if (data[i] != null) {
data[i] = data[i + 1];
}
}
}
index--;
} else {
isEmpty = true;
}
this.notify();
}
}