这是java多线程经常会遇到的问题。供初学者学习。
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Hello {
public static void main(String[] args) {
ExecutorService executorService=Executors.newCachedThreadPool();
BlockingQueue queue=new ArrayBlockingQueue(5);
Hello hello=new Hello();
Producer producer= hello.new Producer(queue);
Consumer consumer= hello.new Consumer(queue);
executorService.execute(producer);
executorService.execute(consumer);
}
class Consumer implements Runnable{
BlockingQueue queue;
public Consumer(BlockingQueue queue){
this.queue=queue;
}
public void run() {
while(true){
try {
Object getObject=queue.take();
Thread.sleep(2000);//取出的时间间隔
System.out.println("取出"+(String)getObject);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable{
BlockingQueue queue;
public Producer(BlockingQueue queue){
this.queue=queue;
}
public void run() {
while(true){
try {
for(int i=0;i<5;i++){
queue.put("num:"+i);
Thread.sleep(1000);//取出的时间间隔
System.out.println("放入"+i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
这是效果图,因为线程是由CPU进行调度,所以结果可能会不同。但是生产者放入,消费者取出的顺序是不会变的。