要求:编写一个后进先出队列,用于存放整数,实现其线程安全
1、队列代码:
public class Queue {
int max = 1000;
int[] queue = new int[max];
int cusor = -1;
public synchronized Integer get() {
while (cusor < 0) {
//返回出错
try {
System.out.println("get wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
--cusor;
int data = queue[cusor + 1];
notifyAll();
return data;
}
public synchronized int put(int data) {
while (cusor >= max - 1) {
//返回出错
try {
System.out.println("put wait");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
++cusor;
queue[cusor] = data;
notifyAll();
return data;
}
}
2、测试代码:
public class Producer extends Thread {
Queue queue;
public Producer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
System.out.println("put " + queue.put(i));
}
}
}
class Consumer extends Thread {
Queue queue;
public Consumer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
System.out.println("get " + queue.get());
}
}
}
class PCTest {
public static void main(String[] args) {
Queue queue1 = new Queue();
Producer producer = new Producer(queue1);
Consumer consumer = new Consumer(queue1);
producer.start();
consumer.start();
}
}