PDA

مشاهده نسخه کامل : متد Join در ریسمان ها



life24
09-08-13, 02:45
با سلام
من چند تا مثال دیدم اما گیج شدم!
وقتی یک ترد رو Join میکنیم . ترد اصلی برنامه دیگه فراخوانی ترد های دیگر رو کنار میزاره و تا اتمام کار ترد فعلی که جوین شده.صبر میکنه؟

Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.



using System;
using System.Threading;

class Example
{
static void Main()
{
Thread t1 = new Thread(() =>
{
Thread.Sleep(4000);
Console.WriteLine("t1 is ending.");
});
t1.Start();

Thread t2 = new Thread(() =>
{
Thread.Sleep(1000);
Console.WriteLine("t2 is ending.");
});
t2.Start();

t1.Join();
Console.WriteLine("t1.Join() returned.");

t2.Join();
Console.WriteLine("t2.Join() returned.");
}
}

/* This example produces the following output:

t2 is ending.
t1 is ending.
t1.Join() returned.
t2.Join() returned.
*/


The Thread.Join method is called on the main thread to let it wait until the other thread finishes
using System;
using System.Threading;
namespace Chapter1
{
public static class Program
{
public static void ThreadMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(“ThreadProc: {0}”, i);
Thread.Sleep(0);
}
}
public static void Main()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Start();
for (int i = 0; i < 4; i++)
{
Console.WriteLine(“Main thread: Do some work.”);
Thread.Sleep(0);
}
t.Join();
}
}
}

ravegoat
12-08-13, 08:44
سلام!

بله؛ Join باعث ميشه ساير Thread ها زمانی آغاز به كار كنند كه ريسمان Join شده كارش به اتمام برسه. با توجه به مثال زير:



Thread t1 = new Thread(Go1);
Thread t2 = new Thread(Go2);
t1.Start();
t1.Join();
t2.Start() ;


ريسمان t2 زمانی كار خودش رو شروع می كنه كه ريسمان t1 پايان بپذيره ولی اگر خط t1.Join رو از حذف كنيم، بلافاصله بعد از ريسمان t1 ريسمان t2 هم شروع به كار می كنه.