CSC352: Defining Number of Threads at Execution Time

From dftwiki3
Revision as of 10:35, 21 February 2017 by Thiebaut (talk | contribs) (Source)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 09:24, 21 February 2017 (EST)


Source


/*
 * UsingQueues.java
 * D. Thiebaut
 * 
 * Illustrates how to use blocking queues to create a way for
 * threads to communicate with each other.
 */
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class UsingQueuesN {
    public static void main(String[] args) throws InterruptedException {
	
	if ( args.length < 1 ) {
	    System.out.println( "Syntax: java UsingQueuesN n" );
	    System.out.println( " where n = # of threads" );
	    return;
	}
	
	int N = Integer.parseInt( args[0] );
	
	BlockingQueue<Integer> toWorkersQ = new ArrayBlockingQueue<Integer>(2*N);
    	BlockingQueue<Integer> fromWorkersQ = new ArrayBlockingQueue<Integer>(2*N);
    	
    	// create a worker and give it the two queues
    	DemoThreadN[] threads = new DemoThreadN[N];
    	
    	for ( int i=0; i<N; i++ ) {
	    DemoThreadN t=new DemoThreadN( i, fromWorkersQ, toWorkersQ );
	    t.start();
	    threads[i] = t;
    	}
	
    	// wait 1/2 second
    	try {
	    Thread.sleep( 500 );
	} catch (InterruptedException e) {
	    e.printStackTrace();
	}
    	
    	// send same amount of work to each worker
    	for ( int i=0; i<N; i++ )
	    toWorkersQ.put( 100 );
    	
    	// wait for answer back from worker
    	for (int i=0; i<N; i++ ) {
	    int x = fromWorkersQ.take();
	    
	    // display the result
	    System.out.println( "x = " + x );
    	}
    }
}

/**
 * DemoThread
 */
class DemoThreadN extends Thread {
	private BlockingQueue<Integer> sendQ;
	private BlockingQueue<Integer> receiveQ;
	private int Id;
	
	DemoThreadN( int Id,
			     BlockingQueue<Integer> sendQ, 
				 BlockingQueue<Integer> receiveQ ) {
		this.Id = Id;
		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*( Id + 1 );
		
		// send results back
		try {
			sendQ.put( x );
		} catch (InterruptedException e) {
			e.printStackTrace();
		}		
	}
}


Output


BlockingQueuesN.jpg