c# - C#中的线程概念

标签 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函数,然后执行循环的Main方法。

最佳答案

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

关于c# - C#中的线程概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33583245/

相关文章:

c# - 定位图形绘制

c# - Windows 窗体 Web 浏览器控制缩放级别

c - 如何保证C中的锁定顺序

java - 从不同线程一起使用 Hibernate 和 JDBC

c# - 算术运算在 VB6 和 C# 中不返回相同值

c# - c# 的正则表达式逐字像字符串(处理 ""-like 转义)

c# - Visual Studio 2015 Intellitest 不适用于 64 位项目

linux - 多个线程定期更新全局变量,而第三个线程等待读取

javascript - 从 asp.net 中的线程将项目添加到表中

java - 如何在一个 AsyncTask 中同时执行多个函数?