简体   繁体   English

Thread.Sleep(0)和Join()的使用

[英]The use of Thread.Sleep(0) and Join()

I am reading a book about multithreading programs and I found this small example : 我正在读一本关于多线程程序的书,我发现了这个小例子:

public static class Program
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(“ThreadProc: {0}”, i);
                Thread.Sleep(0);
            }
        }
        public static void Main()
        {
            Thread t = new Thread(new ThreadStart(ThreadMethod));
            t.Start();
            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine(“Main thread: Do some work.”);
                Thread.Sleep(0);
            }
            t.Join();
        }
    }

I've got too many questions in mind: 我有太多问题:

1) What's the use of Thread.Sleep(0) , I mean, I've tried the two cases : with or without Thread.Sleep(0) , no big difference in runtime 1) Thread.Sleep(0)的用途是什么,我的意思是,我尝试了两种情况:有或没有Thread.Sleep(0) ,运行时没有太大区别

2) Is t.Join() really usefull here, since it is in the end of the Main method ? 2) t.Join()在这里真的很有用,因为它在Main方法的最后?

Thread.Sleep(0) will yield to other threads that don't have lower priority then yours: Thread.Sleep(0)将屈服于其他没有低优先级的线程:

If the value of the millisecondsTimeout argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. 如果millisecondsTimeout参数的值为零,则线程将其时间片的剩余部分放弃到准备运行的任何具有相同优先级的线程。 If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended. 如果没有其他具有相同优先级的线程准备好运行,则不会暂停执行当前线程。

So in case of this example it is something that tries to make threads run at approximately equal pace. 因此,在这个例子的情况下,尝试使线程以大致相同的速度运行。

The Thread.Join usage suggests that it is needed not to end your program before your threads finish their work. Thread.Join用法表明,在线程完成工作之前,不需要结束程序。 However, as Scott Chamberlain points out, by default IsBackground property is false so your threads are foreground threads, and will keep the program running by themselves until they've finished their work. 但是,正如Scott Chamberlain指出的那样,默认情况下IsBackground属性为false因此您的线程是前台线程,并且将保持程序自己运行,直到它们完成工作。 If your program had something more to do, and usually has, that needs the results of threads' work then the Join call would really be essential. 如果你的程序有更多事情要做,并且通常有,那需要线程工作的结果,那么Join调用真的很重要。

Try setting the IsBackground property to different values, and experiment with removing the Join call to see what happens. 尝试将IsBackground属性设置为不同的值,并尝试删除Join调用以查看发生的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM