多线程在BlockingQueue中读写数据

demo

一个简单的案例,使用多线程在BlockingQueue中读写数据

public class BlockQueueClient {
     

    int threadNum=4;
    int clientNum=2000;

    private BlockingQueue<String> queue = new LinkedTransferQueue<String>();

        public static void main(String[] args) {
     

                BlockQueueClient blockQueueClient = new BlockQueueClient();
                blockQueueClient.producer();
                blockQueueClient.consumer();


        }

    public void producer() {
     

            ExecutorService exec = Executors.newFixedThreadPool(threadNum);

            final CountDownLatch doneSignal = new CountDownLatch(clientNum);

            if (queue.isEmpty()){
     
                    Runnable run = new Runnable() {
     

                     public void run() {
     
                        try {
     

                           queue.offer("1");
                           System.out.println("线程写入BlockingQueue");
                           Thread.sleep(1000);
                           
                        } catch (Exception e) {
     
                            e.printStackTrace();
                        }
                                    doneSignal.countDown();// 每调用一次countDown()方法,计数器减1
                        }
                    };
                    exec.execute(run);
            }

    }

    public void consumer () {
     

            ExecutorService exec = Executors.newFixedThreadPool(3);

            for (int i = 0; i < 20; i++) {
     

             Runnable run = new Runnable() {
     
              @Override
               public void run() {
     
                  System.out.println("从BlockingQueue中读取数据:"+queue.poll());
               }
              };
              exec.execute(run);
            }
    }

}

你可能感兴趣的:(java)