Use Join() to wait for threads to end : Thread Join « Thread « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / CSharp Tutorial » Thread » Thread Join 




using System; 
using System.Threading; 
 
class MyThread 
  public int count; 
  public Thread thrd; 
 
  public MyThread(string name) { 
    count = 0
    thrd = new Thread(this.run)
    thrd.Name = name; 
    thrd.Start()
  
 
  void run() { 
    Console.WriteLine(thrd.Name + " starting.")
 
    do 
      Thread.Sleep(500)
      Console.WriteLine("In " + thrd.Name + 
                        ", count is " + count)
      count++; 
    while(count < 10)
 
    Console.WriteLine(thrd.Name + " terminating.")
  

 
class MainClass 
  public static void Main() { 
    Console.WriteLine("Main thread starting.")
 
    MyThread mt1 = new MyThread("Child #1")
    MyThread mt2 = new MyThread("Child #2")
    MyThread mt3 = new MyThread("Child #3")
 
    mt1.thrd.Join()
    Console.WriteLine("Child #1 joined.")
 
    mt2.thrd.Join()
    Console.WriteLine("Child #2 joined.")
 
    mt3.thrd.Join()
    Console.WriteLine("Child #3 joined.")
 
    Console.WriteLine("Main thread ending.")
  
}
Main thread starting.
Child #1 starting.
Child #2 starting.
Child #3 starting.
In Child #1, count is 0
In Child #2, count is 0
In Child #3, count is 0
In Child #1, count is 1
In Child #2, count is 1
In Child #3, count is 1
In Child #1, count is 2
In Child #2, count is 2
In Child #3, count is 2
In Child #1, count is 3
In Child #2, count is 3
In Child #3, count is 3
In Child #1, count is 4
In Child #2, count is 4
In Child #3, count is 4
In Child #1, count is 5
In Child #2, count is 5
In Child #3, count is 5
In Child #1, count is 6
In Child #2, count is 6
In Child #3, count is 6
In Child #1, count is 7
In Child #2, count is 7
In Child #3, count is 7
In Child #1, count is 8
In Child #2, count is 8
In Child #3, count is 8
In Child #1, count is 9
Child #1 terminating.
In Child #2, count is 9
Child #2 terminating.
In Child #3, count is 9
Child #3 terminating.
Child #1 joined.
Child #2 joined.
Child #3 joined.
Main thread ending.














20.5.Thread Join
20.5.1.Use Join() to wait for threads to end
20.5.2.Threads Joining
20.5.3.Thread joins
20.5.4.Block until a thread finishes, or timeout after 2 seconds
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.