C#中的线程概念

时间:2015-11-07 13:24:54

标签: c# multithreading

我是C#的新手,仍在学习线程概念。我写了一个程序如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication17
{
  class Program
  {
    static void Main(string[] args)
    {
        System.Threading.ThreadStart th1 = new System.Threading.ThreadStart(prnt);
        Thread th = new Thread(th1);
        th.Start();
        bool t = th.IsAlive;
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine(i + "A");
        }
    }

    private static void prnt()
    {
        for (int i = 0; i < 10; i ++)
        {
            Console.WriteLine(i + "B");
        }
    }
  }
}

我期待输出如下: -

1A
2A
1B
3A
2B...

因为我相信主线程和新创建的线程都应该同时执行。

但输出是有序的,首先调用prnt函数,然后执行for Main方法。

3 个答案:

答案 0 :(得分:3)

也许10的cicle不足以看到两个线程同时运行。 使用更长的循环或在循环迭代中放置Thread.Sleep(100)。 启动一个线程非常昂贵。可能的情况是,由于线程启动所需的时间,你在线程循环开始之前执行主循环

答案 1 :(得分:2)

我同意您之前需要添加Thread.Sleep(几秒* 1000)的答案

我建议你阅读这篇关于线程的文章 https://msdn.microsoft.com/ru-ru/library/system.threading.thread(v=vs.110).aspx

    static void Main(string[] args)
    {
        Thread th = new Thread(prnt);
        th.Start();
        for (int i = 0; i < 10; i++)
        {
            //sleep one second
            Thread.Sleep(1000);
            Console.WriteLine(i + "A");
        }
        //join the basic thread and 'th' thread 
        th.Join();
    }
    private static void prnt()
    {
        for (int i = 0; i < 10; i++)
        {
            //sleep one second
            Thread.Sleep(1000);
            Console.WriteLine(i + "B");
        }
    }

答案 2 :(得分:1)

已更新:进程用于隔离在该进程的上下文中运行的应用程序和线程。

通过这种方式,操作系统可以更轻松地管理不同的应用程序,管理崩溃和上下文切换(提供给每个应用程序的时间段由CPU执行)。背后的想法只是在预定义的时间段内运行线程,当应用程序运行所允许的时间结束时,CPU切换到要执行的其他线程。

将Threading类用于应用程序中的小型异步任务。

在下面的示例中,您将了解如何使用System.Threading命名空间创建新线程。注意如何调用t.Join()来等待新线程完成。

请注意,Spleep(1)将强制更改上下文,这就是与您相关的示例。尝试将其更改回零并查看结果。

using System;
using System.Threading;

namespace Chapter1
{
    public static class Threads1
    {
        public static void ThreadMethod()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("ThreadProc: {0}", i);
                Thread.Sleep(1);
            }
        }
        public static void Main(string[] args)
        {
            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(1);
            }
            t.Join();

            Console.Read();
        }
    }
}
// OUTPUT:
//Main thread: Do some work.
//ThreadProc: 0
//ThreadProc: 1
//Main thread: Do some work.
//ThreadProc: 2
//Main thread: Do some work.
//ThreadProc: 3
//Main thread: Do some work.
//ThreadProc: 4
//ThreadProc: 5
//ThreadProc: 6
//ThreadProc: 7
//ThreadProc: 8
//ThreadProc: 9