线程如何工作 [英] how does work thread

查看:75
本文介绍了线程如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以按照以下代码解释其工作方式:



Can Anyone explain how does work following code:



class Threading1
    {
        static void Main()
        {
            ThreadStart job = new ThreadStart(ThreadJob);
            Thread thread = new Thread(job);
            thread.Start();

            for (int i = 0; i < 4; i++)
            {
                Console.WriteLine("First Thread: {0}", i);
                Thread.Sleep(1000);
            }
        }

        static void ThreadJob()
        {
            for (int i = 0; i < 8; i++)
            {
                Console.WriteLine("Remaining Threads: {0}", i);
                Thread.Sleep(500);
            }
        }
    }

推荐答案

此代码仅启动一个线程,该线程记录剩余线程:{x}"行8次,中间间隔500毫秒,而该行第一个线程:{x}被记录了几次,并且之间有1000ms的暂停时间.日志字符串实际上导致错误的假设,即您正在启动多个线程,显然不是这种情况.
main函数也不等待实际的一个线程完成,因此不确定该线程是否在Main()的末尾完成.
This code simply starts ONE thread which logs the line "Remaining Threads: {x}" 8 times with a 500ms pause between, while the line "First Thread:{x}" is logged several times with a 1000ms pause in between. The log strings are actually leading to the wrong assumption that you are starting several threads, which is clearly not the case.
The main function also does not wait for the actual ONE thread to be finished, so it is not sure that the thread is done at the end of Main().


这篇关于线程如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆