Strumenti Utente

Strumenti Sito


lpr-b:lpr-b-09:soluzioni

Questa è una vecchia versione del documento!


Tasks e Threads: Es 1

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
public class PrintTask implements Runnable
{
	private int id;
	private int max;
	private static Random generator = new Random();
 
	public PrintTask(int id, int max)
	{
		this.id = id;
		this.max = max;
	}
 
	public void run()
	{
		for(int i = 0; i < max; i++)
		{
			System.out.println(i + "[Task" + id + "]");
			try
			{
				Thread.sleep(generator.nextInt(1000));
			}catch(InterruptedException exception)
			{
				exception.printStackTrace();
			}
		}
	}
 
	public static void main(String[] args)
	{
		int nTasks = 5;
		int max = 10;
		if(args.length > 1)
		{
			nTasks = Integer.parseInt(args[0]);
			max = Integer.parseInt(args[1]);
		}
		ExecutorService threadExecutor = Executors.newCachedThreadPool();
		for(int i = 0; i < nTasks; i++)
			threadExecutor.execute(new PrintTask(i, max));
 
		threadExecutor.shutdown();
	}
}

Tasks e Threads: Es 2

public class SleepTask implements Runnable
{
	private long start = 0;
	private long end = 0;
	private final long SLEEP_TIME = 10000;
 
	public void run()
	{
		try
		{
			start = System.currentTimeMillis();
			Thread.sleep(SLEEP_TIME);
		}catch(InterruptedException x)
		{
			end = System.currentTimeMillis();
			System.out.println("TaskSleep - interrotto dopo " + (end - start) + " ms");
		}
	}
 
	public static void main(String[] args)
	{
		final long MAX_TIME = 5000;
		SleepTask task = new SleepTask();
		Thread t = new Thread(task);
		System.out.println("main - avvio il thread");
		t.start();
 
		try
		{
			Thread.sleep(MAX_TIME);
		}catch(InterruptedException x){}
 
		System.out.println("main - eseguo la interrupt sul thread");
		t.interrupt();
		System.out.println("main - fine del main");
	}
}
lpr-b/lpr-b-09/soluzioni.1256241220.txt.gz · Ultima modifica: 22/10/2009 alle 19:53 (16 anni fa) da Andrea Corradini

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki