当前位置 : 主页 > 编程语言 > c++ >

producer-consumer

来源:互联网 收集:自由互联 发布时间:2021-07-03
producer-consumer package com.huidev.concurrency.ThreadPoolExecutor.ProducerConsumer;import java.util.concurrent.BlockingQueue;/** * Created by hui_stone on 2017/4/22 0022. */public class Producer implements Runnable { private final Blockin
producer-consumer
package com.huidev.concurrency.ThreadPoolExecutor.ProducerConsumer;
import java.util.concurrent.BlockingQueue;
/**
 * Created by hui_stone on 2017/4/22 0022.
 */
public class Producer implements Runnable {
    private final BlockingQueue
 
   sharedQueue;
    private int threadNo;
    public Producer(BlockingQueue
  
    sharedQueue,int threadNo) { this.threadNo = threadNo; this.sharedQueue = sharedQueue; } @Override public void run() { for(int i=1; i<= 5; i++){ try { int number = i+(10*threadNo); System.out.println("Produced:" + number + ":by thread:"+ threadNo); sharedQueue.put(number); } catch (Exception err) { err.printStackTrace(); } } } } public class Consumer implements Runnable { private final BlockingQueue
   
     sharedQueue; private int threadNo; public Consumer (BlockingQueue
    
      sharedQueue,int threadNo) { this.sharedQueue = sharedQueue; this.threadNo = threadNo; } @Override public void run() { // while(true){ while(!Thread.currentThread().isInterrupted()) { try { int num = sharedQueue.take(); System.out.println("Consumed: " + num + ":by thread:" + threadNo); } catch (Exception err) { err.printStackTrace(); } } } } public class Main { public static void main(String[] args) { BlockingQueue
     
       shardingQueue = new LinkedBlockingDeque
      
       (); ExecutorService pes = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue
       
        ()); ExecutorService ces = new ThreadPoolExecutor(2, 4, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue
        
         ()); pes.execute(new Producer(shardingQueue,1)); ces.execute(new Consumer(shardingQueue,1)); ces.execute(new Consumer(shardingQueue,2)); pes.shutdown(); ces.shutdown(); } }
        
       
      
     
    
   
  
 
网友评论