2

我有以下 C# 代码

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

4

1 回答 1

7

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

因为这不是 .NET 和Windows操作系统文档都不确定的(我想您使用的是 Windows)

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

线程将由操作系统调度执行。MSDN:“导致线程被安排执行。”

为什么 ThreadProc: 0 在 Main thread: 每次执行时启动第二个线程后没有立即打印?

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

于 2013-04-17T15:41:24.960 回答