2013-04-17 172 views
2

我有the following C# code線程執行順序

using System; 
using System.Threading; 

// Simple threading scenario: Start a static method running 
// on a second thread. 
public class ThreadExample { 
    // The ThreadProc method is called when the thread starts. 
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends. 
    public static void ThreadProc() { 
     for (int i = 0; i < 10; i++) { 
      Console.WriteLine("ThreadProc: {0}", i); 
      // Yield the rest of the time slice. 
      Thread.Sleep(0); 
     } 
    } 

    public static void Main() { 
     Console.WriteLine("Main thread: Start a second thread."); 
     // The constructor for the Thread class requires a ThreadStart 
     // delegate that represents the method to be executed on the 
     // thread. C# simplifies the creation of this delegate. 
     Thread t = new Thread(new ThreadStart(ThreadProc)); 

     // Start ThreadProc. Note that on a uniprocessor, the new 
     // thread does not get any processor time until the main thread 
     // is preempted or yields. Uncomment the Thread.Sleep that 
     // follows t.Start() to see the difference. 
     t.Start(); 
     //Thread.Sleep(0); 

     for (int i = 0; i < 4; i++) { 
      Console.WriteLine("Main thread: Do some work."); 
      Thread.Sleep(0); 
     } 

     Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends."); 
     t.Join(); 
     Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program."); 
     Console.ReadLine(); 
    } 
} 

這是因爲我學的是線程大學很長一段時間,我還記得的唯一的事情是:

線程的執行是相當難以預測,可能因操作系統不同而不同。

所以真正的問題是:爲什麼我不能肯定,甚至不是關於第一執行ThreadProc的嗎?當我執行t.Start()時會發生什麼?爲什麼ThreadProc: 0在每次執行後都不會立即打印Main thread: Start a second thread

回答

7

爲什麼我不能確定沒有關於ThreadProc的第一次執行?

因爲這是不確定的既不是.NET也不Windows OS文檔(我想你使用的是Windows)

什麼,當我執行恰巧t.Start()?

線程將由OS調度執行。 MSDN:「導致線程被安排執行。」

爲什麼ThreadProc:0不會立即打印主線程:在每次執行中啓動一個 第二個線程?

因爲有Thread.Start()呼叫,實際線程之間的一些延遲啓動