blockingQueue

//take put 都是阻塞的    

package threadimp;

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {
BlockingQueue queue;
public Producer(BlockingQueue queue) {
    this.queue = queue;
}

@Override
public void run() {
    // TODO Auto-generated method stub
    String name = Thread.currentThread().getName();
    System.out.println("producing " + name);
    try {
        queue.put(name);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}





package threadimp;

import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{
BlockingQueue queue;
public Consumer(BlockingQueue queue) {
    this.queue = queue;
}
@Override
public void run() {
    // TODO Auto-generated method stub
    System.out.println("consuming " + Thread.currentThread().getName());
    
    try {
        String temp = queue.take();
        System.out.println("get " + temp);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
}

}



package threadimp;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class PCTest {
public static void main(String[] args) {
    BlockingQueue queue = new LinkedBlockingQueue<>(2);
    Consumer consumer = new Consumer(queue);
    Producer producer = new Producer(queue);
for (int i = 0; i < 3; i++) {
    new Thread(producer, "Producer " + i).start();
}

for (int i = 0; i < 5; i++) {
    new Thread(consumer, "Consumer " + i).start();
}
//new Thread(producer, "Producer" + 5).start();
}
}

你可能感兴趣的:(blockingQueue)