java

/**
* productor create the product,and does not care consumer
*/
class Productors extends Thread{

private final BlockingQueue<String> queue;

public Productors( BlockingQueue<String> queue){this.queue = queue;}

@Override
public void run() {

try {
queue.put(Double.toString(Math.random()));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

}

}
class Consumers extends Thread{

private final BlockingQueue<String> queue;

public Consumers( BlockingQueue<String> queue){this.queue = queue;}

@Override
public void run() {

try {
System.out.println(queue.take());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

}
}
public class Thread2_7 {

public static void main(String[] args) {

//share queue for productor and consumer
BlockingQueue<String> queue = new ArrayBlockingQueue<>(20);

for(int i=0; i< 10 ;i++){

new Productors(queue).start();
new Consumers(queue).start();
}


}

你可能感兴趣的:(java)