阻塞队列 Future 线程池 AtomicInteger简单示例

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{
	   private final BlockingQueue queue;
	   
	   public Consumer(BlockingQueue q) { 
		   queue = q; 
		   }
	   
	   public void run() {
	     try {
	      for(int i=0;i<100;i++){
	      consume(queue.take());
	      }
	     } catch (InterruptedException ex) {}
	   }
	   void consume(Object x) {
	   System.out.println("cousume"+x.toString());
	   }
}
import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable{
	   private final BlockingQueue queue;
	   public Producer(BlockingQueue q)
	   { 
		   queue = q; 
	   }
	   
	   public void run() {
	     try {
	      for(int i=0;i<100;i++){
	      queue.put(produce());
	      }
	      
	     } catch (InterruptedException ex) {}
	   }
	   
	   String produce() {
	   String temp=""+(char)('A'+(int)(Math.random()*26));
	   System.out.println("produce"+temp);
	   return temp;
	   }
}
//生产者 消费者 模式  ArrayBlockingQueue LinkedBlockingQueue 阻塞队列
    	BlockingQueue<String> queue1=new LinkedBlockingQueue<String>(5);
//    	
    	Producer p=new Producer(queue1);
    	Consumer c1=new Consumer(queue1);
    	Consumer c2=new Consumer(queue1);
    	
    	new Thread(p).start();
    	new Thread(c1).start();
    	new Thread(c2).start();

List<Callable<Long>> callList = new ArrayList<Callable<Long>>();add一些Callable的实现类,多线程求和计算。

int threadCounts = 19;// 使用的线程数
		long sum = 0;
		ExecutorService exec1 = Executors.newFixedThreadPool(threadCounts);
		List<Callable<Long>> callList = new ArrayList<Callable<Long>>();
		// 生成很大的List
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i <= 1000000; i++) {
			list.add(i);
		}
		int len = list.size() / threadCounts;// 平均分割List
		// List中的数量没有线程数多(很少存在)
		if (len == 0) {
			threadCounts = list.size();// 采用一个线程处理List中的一个元素
			len = list.size() / threadCounts;// 重新平均分割List
		}
		for (int i = 0; i < threadCounts; i++) {
			final List<Integer> subList;
			if (i == threadCounts - 1) {
				subList = list.subList(i * len, list.size());
			} else {
				subList = list.subList(i * len,
						len * (i + 1) > list.size() ? list.size() : len
								* (i + 1));
			}
			// 采用匿名内部类实现
			callList.add(new Callable<Long>() {
				public Long call() throws Exception {
					long subSum = 0L;
					for (Integer i : subList) {
						subSum += i;
					}
					System.out.println("分配给线程:"
							+ Thread.currentThread().getName()
							+ "那一部分List的整数和为:\tSubSum:" + subSum);
					return subSum;
				}
			});
		}
		List<Future<Long>> futureList = exec1.invokeAll(callList);
		for (Future<Long> future : futureList) {
			sum += future.get();
		}
		exec1.shutdown();
		System.out.println(sum);

AtomicInteger的简单举例

// 阻塞队列,能容纳100个文件
        final BlockingQueue<File> queue = new LinkedBlockingQueue<File>(100);
        // 线程池
        final ExecutorService exec = Executors.newFixedThreadPool(5);
        final File root = new File("D:\\jpg");
        // 完成标志
        final File exitFile = new File("");
        // 原子整型,读个数
        // AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
        final AtomicInteger rc = new AtomicInteger();
        // 原子整型,写个数
        final AtomicInteger wc = new AtomicInteger();
        // 读线程
        Runnable read = new Runnable() {
            public void run() {
                scanFile(root);
                scanFile(exitFile);
            }

            public void scanFile(File file) {
                if (file.isDirectory()) {
                    File[] files = file.listFiles(new FileFilter() {
                        public boolean accept(File pathname) {
                            return pathname.isDirectory() || pathname.getPath().endsWith(".jpg");
                        }
                    });
                    for (File one : files)
                        scanFile(one);
                } else {
                    try {
                        // 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
                        int index = rc.incrementAndGet();
                        System.out.println("Read0: " + index + " " + file.getPath());
                        // 添加到阻塞队列中
                        queue.put(file);
                    } catch (InterruptedException e) {

                    }
                }
            }
        };
        // submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
        exec.submit(read);

        // 四个写线程
        for (int index = 0; index < 4; index++) {
            // write thread
            final int num = index;
            Runnable write = new Runnable() {
                String threadName = "Write" + num;

                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(randomTime());
                            // 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
                            int index = wc.incrementAndGet();
                            // 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
                            File file = queue.take();
                            // 队列已经无对象
                            if (file == exitFile) {
                                // 再次添加"标志",以让其他线程正常退出
                                queue.put(exitFile);
                                break;
                            }
                            System.out.println(threadName + ": " + index + " " + file.getPath());
                        } catch (InterruptedException e) {
                        }
                    }
                }

            };
            exec.submit(write);
        }
        exec.shutdown();
    }


















转载于:https://my.oschina.net/rouchongzi/blog/172448

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值