Lune03
Messages postés11Date d'inscriptionmercredi 31 octobre 2007StatutMembreDernière intervention 4 mars 2011
-
27 sept. 2010 à 12:32
Lune03
Messages postés11Date d'inscriptionmercredi 31 octobre 2007StatutMembreDernière intervention 4 mars 2011
-
28 sept. 2010 à 14:57
Bonjour,
Pour me familiariser avec la fonction "Join", j'ai lancé le programme suivant, mais contrairement à ce que j'attendai, la fonction "thread0.Join()" à privilègié l'execussion des 3 threads alors que je m'attendai à ce que seul le thread0 soit finalisé (et que les 3 autres : current, Thr2 et Thr3 soient en attente) ?????
Si quelqu'un peut m'éclairer !
Cordialement
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadJoin2
{
class Program
{
public static void run0()
{
for (int i0 = 1; i0 < 100; i0++)
{
System.Console.Write(" thread0=" + i0);
Thread.Sleep(10);
}
}
public static void run1()
{
for (int i0 = 1; i0 < 100; i0++)
{
System.Console.Write(" thread1=" + i0);
Thread.Sleep(10);
}
}
public static void run2()
{
for (int i0 = 1; i0 < 100; i0++)
{
System.Console.Write(" thread2=" + i0);
Thread.Sleep(10);
}
}
public static void etatsThreads(Thread principal, Thread thrd1, Thread thrd2, Thread thrd3)
{
System.Console.WriteLine("\n" + principal.Name + " : " + principal.ThreadState);
System.Console.WriteLine(thrd1.Name + " : " + thrd1.ThreadState);
System.Console.WriteLine(thrd2.Name + " : " + thrd2.ThreadState);
System.Console.WriteLine(thrd3.Name + " : " + thrd3.ThreadState);
}
static void Main(string[] args)
{
Console.Clear();
Console.WriteLine("Lancement des threads :");
Thread principal = Thread.CurrentThread;
principal.Name = "principal";
Thread thread0 = new Thread(new ThreadStart(run0));
thread0.Name = "thread0";
Thread thread1 = new Thread(new ThreadStart(run1));
thread1.Name = "thread1";
Thread thread2 = new Thread(new ThreadStart(run2));
thread2.Name = "thread2";
etatsThreads(principal, thread0, thread1, thread2);
thread0.Start();
thread1.Start();
thread2.Start();
System.Console.WriteLine("\n-> All Threads started !");
etatsThreads(principal, thread0, thread1, thread2);
for (int i = 1; i < 20; i++)
{
System.Console.WriteLine(" i = " + i);
Thread.Sleep(10);
}
etatsThreads(principal, thread0, thread1, thread2);
System.Console.WriteLine("\n-> THR0 JOIN(D) !");
thread0.Join();
System.Console.WriteLine("\n-> THR0 JOIN(F) !");
etatsThreads(principal, thread0, thread1, thread2);
for (int i = 20; i < 100; i++)
{
System.Console.WriteLine(" i = " + i);
Thread.Sleep(10);
}
System.Console.WriteLine("fin de tous les threads.");
System.Console.Read();
}
}
}
captainFoyd
Messages postés11Date d'inscriptionmardi 28 septembre 2010StatutMembreDernière intervention30 avril 2012 28 sept. 2010 à 12:04
Effectivement, le thread0.Join() met uniquement le thread principal en attente jusqu'à ce que le thread0 soit terminé. L'exécution des autres threads (1 et 2) se poursuit au même rythme.