Strumenti Utente

Strumenti Sito


lpr-b-2007-2008:maintpconcurr
package threadPoolConcurrency;
 
import java.util.concurrent.*;
 
 
public class ProvaThreadPool {
 
	public static void main(String[] args) {
 
		final int N = 16;		// numero dei task da calcolare
		final int T = 4;		// numero minimo di thread nel pool 
		// final int MAX_T = 8;    // numero massimo di thread nel pool 
 
		ExecutorService tpe = null; 		// creazione dell'esecutore
		tpe = // new ThreadPoolExecutor(T,MAX_T,10000L,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
			Executors.newFixedThreadPool(T);
 
		// creazione del repository per i risultati
		Repository<Integer> results = new Repository<Integer>();
		// creazione del thread stampatore
		Stampatore<Integer> stampatore = new Stampatore<Integer>(results);
		stampatore.start();
		// funzione da calcolare
		Compute<Integer,Integer> fun = new FunzioneSemplice();
 
		// questo sostituisce il codice del generatore:    
		for(int i=0; i<N; i++) {                 // per ogni task,
			Task t = new Task(i,fun,results);	 // crea un nuovo Task Runnable
			tpe.execute(t);						 // e lo passa al ThreadPoolExceutor
			try {Thread.sleep(10); } catch(InterruptedException e) {e.printStackTrace();}  // attende un po' prima di generarne un altro
		}
		System.out.println("Shutdown ...");
		tpe.shutdown();		// equivalente alla dichiarazione di fine stream del generatore 
		System.out.println("Attesa terminazione ...");
		try {
			tpe.awaitTermination(50000L, TimeUnit.MILLISECONDS);   // attesa della terminazione
		} catch (InterruptedException e) {
			System.out.println("ThreadPoolExecutor non ha terminato l'esecuzione: scatta timeout");
		}
		System.out.println("Tutti i thread del pool sono terminati\nTerminazione Stampatore ...");
		stampatore.interrupt();	// come prima
		System.out.println("Terminazione main");
		// fine lavori ...
		return;		
	}
 
}
lpr-b-2007-2008/maintpconcurr.txt · Ultima modifica: 19/09/2008 alle 14:08 (16 anni fa) (modifica esterna)