线程执行顺序

时间:2013-04-17 15:35:15

标签: c# .net multithreading

我有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();
    }
}

自从我研究大学以来,很长一段时间,我唯一记得的是:

  

线程执行非常难以预测,并且可能因underlayng而异   OS。

所以真正的问题是:为什么我不能确定甚至没有关于ThreadProc的第一次执行?执行t.Start()时会发生什么?为什么ThreadProc: 0在每次执行中都不会立即打印Main thread: Start a second thread

1 个答案:

答案 0 :(得分:7)

  

为什么我不能确定第一次执行ThreadProc?

因为这既不是.NET也不是Windows操作系统文档(我想你使用的是Windows)不确定

  

执行t.Start()时会发生什么?

线程将由OS调度执行。 MSDN:&#34;导致线程被安排执行。&#34;

  

为什么ThreadProc:0不会在主线程后立即打印:启动a   每次执行中的第二个线程?

因为Thread.Start()调用与实际线程启动之间存在一些延迟