实现一个队列。
队列的应用场景为:
一个生产者线程将 int 类型的数入列,一个消费者线程将 int 类型的数出列
思路:
多线程...
public class Q34 {
public static Queue<Integer> queue = new LinkedList<Integer>();
public static void main(String[] args) throws Exception {
Thread producer = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(true)
{
if(queue.size()>=1)
System.out.println("poll:"+queue.poll());
Thread.sleep(1000);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Thread coustomer = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub.
try {
while(true)
{
int num = (int)Math.round(Math.random()*99+1);
System.out.println("push:"+num);
queue.add(num);
Thread.sleep(1000);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
producer.start();
coustomer.start();
}
}