zoukankan      html  css  js  c++  java
  • 多线程的并发运行应用(生产者消费者模式)

     
    
    

    在实际的开发中我们为了提高CPU的利用率,也提高程序的运行效率,我们常常使用多线程进行对数据进行并发处理。以下我举一个多线程并发运行的实例,大致意思就是

    一个简单的生产者消费者模式,二个线程进行存数据。一个线程进行取数据。

    import java.util.concurrent.ArrayBlockingQueue;
    import java.util.concurrent.BlockingQueue;
    
    public class BlockingQueueTest {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		final BlockingQueue queue = new ArrayBlockingQueue(3);
    
    		for (int i = 0; i < 2; i++) {
    			new Thread(new Runnable() {
    
    				@Override
    				public void run() {
    					while (true) {
    						try {
    							Thread.sleep((long) Math.random() * 1000);
    							System.out.println(Thread.currentThread().getName()
    									+ " 准备放数据 ");
    							queue.put(1);
    							System.out.println(Thread.currentThread().getName()
    									+ " 队列中有数据 " + queue.size() + " 个");
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    					}
    				}
    			}).start();
    
    		}
    		new Thread(new Runnable() {
    
    			@Override
    			public void run() {
    				while (true) {
    					try {
    						Thread.sleep((long) Math.random() * 1000);
    						System.out.println(Thread.currentThread().getName()
    								+ " 准备取数据 ");
    						queue.take();
    						System.out.println(Thread.currentThread().getName()
    								+ " 队列中剩余数据 " + queue.size() + " 个");
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		}).start();
    	}
    }
    
    能够自己实际測试一下。能够执行。

    自己能够查看结果即明确多线程的应用

  • 相关阅读:
    如何检测死锁并快速定位死锁位置
    几种线程本地存储变量和普通变量的性能比较
    multi_index_container性能测试
    [高并发引擎]定时器模块
    [高并发引擎]Log模块
    静态博客教程 1:hexo + github
    蛇形填数
    实现简单的 ls 命令
    静态库与动态库的创建和使用
    用两个栈实现队列
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/6881768.html
Copyright © 2011-2022 走看看