blockingqueuetest.java

来自「用NETBEANS做的一个关于Java的小小的demo.大家赐教」· Java 代码 · 共 61 行

JAVA
61
字号
/*
 * BlockingQueueTest.java
 *
 * Created on 2007年9月14日, 下午1:10
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package product_consumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 *
 * @author Administrator
 */
public class BlockingQueueTest {
    static BlockingQueue<String> basket;
    public BlockingQueueTest() {
        //定义了一个大小为2的BlockingQueue,也可根据需要用其他的具体类
        basket = new ArrayBlockingQueue<String>(2);
    }
    class Producor implements Runnable {
        public void run() {
            while(true){
                try {
                    //放入一个对象,若basket满了,等到basket有位置
                    basket.put("An apple");
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    class Consumer implements Runnable {
        public void run() {
            while(true){
                try {
                    //取出一个对象,若basket为空,等到basket有东西为止
                    String result = basket.take();
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
    public void execute(){
        for(int i=0; i<10; i++){
            new Thread(new Producor()).start();
            new Thread(new Consumer()).start();
        }
    }
    public static void main(String[] args){
        BlockingQueueTest test = new BlockingQueueTest();
        test.execute();
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?