2013-04-17 174 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()呼叫,实际线程之间的一些延迟启动