using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; /* * Esercizio 2: Monitoraggio dello Stato di un Thread * Obiettivo: Imparare a controllare lo stato di un thread durante la sua esecuzione. * Richieste: * Scrivere un programma che crea tre thread * - Assegni un nome ad ogni thread (es. Primo, Secondo, Terzo) * - Ogni thread stampa il proprio nome ed esegue un'operazione lunga che dura 10 secondi. * - Il main stampa lo stato di ogni thread e * - se non è "vivo" lo avvia thread. * - Attende 3 secondo. * - Stampa di nuovo lo stato di ogni thread e se è "vivo" * - Usa `Join()` per attendere la sua terminazione. * - Stampa per l'ultima volta lo stato dei thread. * - Analizza e commenta nel codice l'output che ti aspetti di vedere per ogni `Conso-le.WriteLine`. */ namespace CompitoThread2 { class Program { static void Main(string[] args) { List t = new List(); for (int i = 0; i < 3; i++) { Thread thread = new Thread(Lavoro); thread.Name = "Thread" + (i + 1); t.Add(thread); } StampaStato(t); foreach (Thread thread in t) { if (thread.ThreadState == ThreadState.Unstarted) thread.Start(thread.Name); } Thread.Sleep(3000); StampaStato(t); foreach (Thread thread in t) { thread.Join(); } StampaStato(t); } static void StampaStato(List t) { foreach (Thread thread in t) { Console.WriteLine("Stato {0}: {1}", thread.Name, thread.ThreadState); } } static void Lavoro(object nome) { if (!(nome is string)) return; Console.WriteLine("Nome Thread: " + nome); Thread.Sleep(10000); } } }