实现一个队列。
队列的应用场景为:
一个生产者线程将 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();
}
}
本文介绍了一个简单的多线程队列应用案例,通过一个生产者线程不断地向队列中添加随机整数,同时一个消费者线程从队列中取出这些整数并打印出来。该例子使用了Java的内置队列实现。
&spm=1001.2101.3001.5002&articleId=9048329&d=1&t=3&u=2def361493754b77b139763de86e45c2)
627

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



