How to run two threads parallel?

后端 未结 4 975
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 15:20

I start two threads with a button click and each thread invokes a separate routine and each routine will print thread name and value of i.

Program runs

4条回答
  •  北海茫月
    2020-12-24 15:58

    They are running in parallel. Here is adjusted code to see it better:

        private void test()
        {
            Thread tid1 = new Thread(new ThreadStart(Thread1));
            Thread tid2 = new Thread(new ThreadStart(Thread2));
    
            tid1.Start();
            tid2.Start();
            Console.Write(string.Format("Done"));
    
        }
        static void Thread1()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.Write(string.Format("Thread1 {0}", i));
                Thread.Yield();
            }
        }
    
        static void Thread2()
        {
            for (int i = 1; i <= 10; i++)
            {
                Console.Write(string.Format("Thread2 {0}", i));
                Thread.Yield();
            }
        }
    

    And here is output: DoneThread1 1Thread2 1Thread1 2Thread2 2Thread1 3Thread2 3Thread1 4Thread2 4Thread1 5Thread2 5Thread1 6Thread2 6Thread1 7Thread2 7Thread1 8Thread2 8Thread1 9Thread2 9Thread1 10Thread2 10

提交回复
热议问题