线程池+阻塞队列 模仿生产者消费者

入口点

package multithreading.BlockingQueue;

import java.util.concurrent.BlockingQueue; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.LinkedBlockingQueue; 
import java.util.concurrent.TimeUnit;
  
/** 
 * Throws exception    Specical value        TimeOut                    Block
 * add(e)                       offer(e)               offer(e,time,unit)         put
 * remove                      poll                   poll(time,unit)             take
 */
public class BlockingQueueTest { 
  
    public static void main(String[] args) throws InterruptedException { 
        // 声明一个容量为10的缓存队列 
    	//SynchronousQueue<String> 只有有人来拿的时候数据才能放的进去
        BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10); 
        
        Producer producer1 = new Producer("rain",queue); 
        Producer producer2 = new Producer("tom",queue); 
        Producer producer3 = new Producer("jack",queue); 
        Consumer consumer = new Consumer(queue); 
  
        // 借助Executors 线程池
        ExecutorService service = Executors.newCachedThreadPool(); 
        // 启动线程 
        service.execute(producer1); 
        service.execute(producer2); 
        service.execute(producer3); 
        service.execute(consumer); 
  
        // 执行3s 
        TimeUnit.SECONDS.sleep(3);
        producer1.stop(); 
        producer2.stop(); 
        producer3.stop(); 
  
        // 退出Executor 
        service.shutdown(); 
    } 
} 


 

 

生产者

 

package multithreading.BlockingQueue;

import java.util.Random; 
import java.util.concurrent.BlockingQueue; 
import java.util.concurrent.TimeUnit; 
import java.util.concurrent.atomic.AtomicInteger;

public class Producer implements Runnable { 
  
	private String name;
    private volatile boolean      isRunning               = true; 
    private BlockingQueue queue; 
    private static AtomicInteger  count                   = new AtomicInteger(); 
    private static final int      DEFAULT_RANGE_FOR_SLEEP = 1000; 
    
    public Producer(String name,BlockingQueue queue) { 
        this.queue = queue; 
        this.name=name;
    } 
  
    public void run() { 
        String data = null; 
        Random r = new Random(); 
  
        System.out.println("启动生产者线程!"+name); 
        try { 
            while (isRunning) { 
                System.out.println(name+"正在生产数据..."); 
                Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP)); 
  
                data = "data:" + count.incrementAndGet(); 
                System.out.println(name+"将数据:" + data + "放入队列..."); 
                if (!queue.offer(data, 2, TimeUnit.SECONDS)) { 
                    System.out.println(name+"放入数据失败:" + data); 
                } 
            } 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
            Thread.currentThread().interrupt(); 
        } finally { 
            System.out.println(name+"退出生产者线程!"); 
        } 
    } 
  
    public void stop() { 
        isRunning = false; 
    } 
  

  
} 


 

消费者

 

package multithreading.BlockingQueue;

import java.util.Random; 
import java.util.concurrent.BlockingQueue; 
import java.util.concurrent.TimeUnit; 


public class Consumer implements Runnable { 
  
	  
    private BlockingQueue<String> queue; 
    private static final int      DEFAULT_RANGE_FOR_SLEEP = 1000; 
    
    public Consumer(BlockingQueue<String> queue) { 
        this.queue = queue; 
    } 
  
    public void run() { 
        System.out.println("启动消费者线程!"); 
        Random r = new Random(); 
        boolean isRunning = true; 
        try { 
            while (isRunning) { 
                System.out.println("消费者正从队列获取数据..."); 
                String data = queue.poll(5, TimeUnit.SECONDS); 
                if (null != data) { 
                    System.out.println("消费者拿到数据:" + data); 
                    System.out.println("消费者正在消费数据:" + data); 
                    Thread.sleep(r.nextInt(DEFAULT_RANGE_FOR_SLEEP)); 
                } else { 
                    // 超过5s还没数据,认为所有生产线程都已经退出,自动退出消费线程。 
                    isRunning = false; 
                } 
            } 
        } catch (InterruptedException e) { 
            e.printStackTrace(); 
            Thread.currentThread().interrupt(); 
        } finally { 
            System.out.println("退出消费者线程!"); 
        } 
    } 

} 


 

你可能感兴趣的:(线程池+阻塞队列 模仿生产者消费者)