本文介绍了线程执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我上大学已经很长时间没有学习这个话题了,我唯一还记得的是:

It's a long time since I studied the thread to university, the only thing that I still remember is:

线程执行是非常不可预测的,并且可能因底层而异操作系统.

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

So the real question is: why I can't be sure not even about the first execution of ThreadProc? What happen when I execute t.Start()? Why ThreadProc: 0 isn't printed immediately after Main thread: Start a second thread in every execution?

推荐答案

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

Because this is nondeterministic neither by .NET nor Windows OS documentation (I suppose you are using Windows)

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

线程将被操作系统调度执行.MSDN:导致线程被安排执行."

Thread will be scheduled by OS for execution. MSDN: "Causes a thread to be scheduled for execution."

为什么 ThreadProc: 0 不会在 Main thread: Start a 之后立即打印每次执行中的第二个线程?

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

Because there is some delay between Thread.Start() call and actual thread start

这篇关于线程执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:46