我是C#的新手,仍在學習線程概念。我寫了一個程序,它是如下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 for循環添加'Thread.Sleep(500);';這將有助於確保他們花費更長時間運行,以便您可以看到發生了什麼。 – JohnLBevan
線程調度是不可預測的,許多程序都會失敗(比賽條件),因爲程序員假定線程不存在某些理想行爲,例如假設線程始終並行運行並處於完美同步狀態。他們不。考慮您的程序如何在帶有大型(100ms +)時間片的操作系統的單線程處理器上運行。 – Dai