加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#中的线程概念

发布时间:2020-12-15 08:47:52 所属栏目:百科 来源:网络整理
导读:我是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 v
我是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方法for循环.

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读