CSC352: Using BlockingQueues

From dftwiki3
Revision as of 09:35, 21 February 2017 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- <bluebox> This page contains a Java program that illustrates how to use BlockingQueues in a threading environment. </bluebox> <br /> =Source= <br /> ::<source lang...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 08:35, 21 February 2017 (EST)


This page contains a Java program that illustrates how to use BlockingQueues in a threading environment.


Source


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class UsingQueues {

	public static void main(String[] args) throws InterruptedException {
		BlockingQueue<Integer> toWorkerQ = new ArrayBlockingQueue<Integer>(2);
    	BlockingQueue<Integer> fromWorkerQ = new ArrayBlockingQueue<Integer>(2);
    	
    	// create a worker and give it the two queues
    	DemoThread t=new DemoThread( fromWorkerQ, toWorkerQ );
    	
    	// start thread 
    	t.start();
    	
    	// wait 1/2 second
    	try {
			Thread.sleep( 500 );
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	
    	// send work to worker
    	toWorkerQ.put( 100 );
    	
    	// wait for answer back from worker
    	int x = fromWorkerQ.take();
    	
    	// display the result
    	System.out.println( "x = " + x );

	}

}

/**
 * DemoThread
 */
class DemoThread extends Thread {
	BlockingQueue<Integer> sendQ;
	BlockingQueue<Integer> receiveQ;

	DemoThread( BlockingQueue<Integer> sendQ, 
				BlockingQueue<Integer> receiveQ ) {
		this.sendQ = sendQ;
		this.receiveQ = receiveQ;
	}
	
	public void run(){ 
		int x=0;
		
		// block until there's something in the queue
		try {
			x = receiveQ.take( );
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		
		// do some computation
		x = x*2;
		
		// send results back
		try {
			sendQ.put( x );
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
}


Output


352b@aurora ~/handout $ javac UsingQueues.java 
352b@aurora ~/handout $ java UsingQueues 
x = 200
352b@aurora ~/handout $