WINDOWS 多线程 [英] Multi threading on WIndows

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

问题描述

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();
    }
}

结果是:

 Main thread: Start a second thread.
 Main thread: Do some work.
 ThreadProc: 0
 Main thread: Do some work.
 ThreadProc: 1
 Main thread: Do some work.
 ThreadProc: 2
 Main thread: Do some work.
 ThreadProc: 3
 Main thread: Call Join(), to wait until ThreadProc ends.
 ThreadProc: 4
 ThreadProc: 5
 ThreadProc: 6
 ThreadProc: 7
 ThreadProc: 8
 ThreadProc: 9
 Main thread: ThreadProc.Join has returned.  Press Enter to end program.

我不明白为什么主线程:做一些工作"之间会出现ThreadProc 0"1"2"3".

I don't understand why "ThreadProc 0" "1" "2" "3" can appear in between " Main thread: Do some work."

谁能帮我解释一下?谢谢!

Can anybody help me explain it? thanks!

推荐答案

t.Start()"行启动另一个线程,该线程在主线程工作时同时运行.

The "t.Start()" line starts the other thread which is running simultaneously while the main thread is doing it's work.

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

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