| Refresh | Home EGTry.com

a blocking queue that block when try to put an object beyond the queue's capacity


ArrayBlockingQueueTest.java

/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.thread;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
public class ArrayBlockingQueueTest {
	private static ArrayBlockingQueue<Job> queue;
	
	
  public static void main(String[] args) {
	  boolean isFIFO=true;
	  int capacity=2;
	  queue=new ArrayBlockingQueue<Job>(capacity,isFIFO);
  
	  Provider provider=new Provider();
	  provider.start();
	  
	  Consumer consumer=new Consumer();
	  consumer.start();
  }
  
  
  public static class Job {
	  public String id;
	  public boolean isLast=false;
	  public Job(String id) {
		  this.id=id;
	  }
  }
  
  public static class Provider extends Thread {
	  
	  @Override
	  public void run() {
		  try {
		  for(int i=0; i<10; i++) {
			  Job job=new Job(i+"");
			  System.out.println("send job "+job.id+" at: "+new Date());			  
			  queue.put(job);
		  }
		  Job lastJob=new Job("Last Job");
		  lastJob.isLast=true;
		  queue.put(lastJob);
		  } catch (InterruptedException e) {
			  System.out.println("Provider thread "+this.getId()+" interrupted");
			  return;
		  }
	  }
  }
  
  public static class Consumer extends Thread {
	  @Override
	  public void run() {
		  while(true) {
			  Job job;
			  try {
				  Thread.sleep(1000);
				  job=queue.take();
				  System.out.println("Got the job: "+job.id);
				  if (job.isLast) {
					  return;
				  }
			  } catch (InterruptedException e) {
				  System.out.println("Consumer thread "+this.getId()+" interrupted");
				  return;
			  }
		  }
	  }
  }
  
}



Output

send job 0 at: Sun Oct 02 23:28:06 CDT 2011
send job 1 at: Sun Oct 02 23:28:06 CDT 2011
send job 2 at: Sun Oct 02 23:28:06 CDT 2011
Got the job: 0
send job 3 at: Sun Oct 02 23:28:07 CDT 2011
Got the job: 1
send job 4 at: Sun Oct 02 23:28:08 CDT 2011
Got the job: 2
send job 5 at: Sun Oct 02 23:28:09 CDT 2011
Got the job: 3
send job 6 at: Sun Oct 02 23:28:10 CDT 2011
Got the job: 4
send job 7 at: Sun Oct 02 23:28:11 CDT 2011
Got the job: 5
send job 8 at: Sun Oct 02 23:28:12 CDT 2011
Got the job: 6
send job 9 at: Sun Oct 02 23:28:13 CDT 2011
Got the job: 7
Got the job: 8
Got the job: 9
Got the job: Last Job