using System;
using System.Threading;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(Method1));
Thread thread2 = new Thread(new ThreadStart(Method2));
thread1.Start();
thread2.Start();
// 主線程結束不會自動結束子線程(前台線程)
// 若需等待可用 thread1.Join() / thread2.Join()
}
public static void Method1()
{
while (true)
{
Console.WriteLine("this is thread : 1");
Thread.Sleep(1000); // 休眠 1 秒
}
}
public static void Method2()
{
while (true)
{
Console.WriteLine("this is thread : 2");
Thread.Sleep(1520); // 休眠 1.52 秒
}
}
}
}
ThreadStart 委派:指向無參無返回值的方法Start():將線程加入排程器,非同步返回Sleep(ms):釋放 CPU 時間片,讓出執行權IsBackground = false,進程會等待所有前台線程結束IsBackground = true,主線程結束時強制終止// ParameterizedThreadStart 接受 object 參數
Thread t = new Thread(obj =>
{
int count = (int)obj;
for (int i = 0; i < count; i++) Console.WriteLine(i);
});
t.Start(10);
new Thread(() =>
{
Console.WriteLine("Lambda thread running");
}).Start();
volatile bool _stop = false;
Thread t = new Thread(() =>
{
while (!_stop) { /* work */ Thread.Sleep(100); }
});
t.Start();
// 別處調用 _stop = true; t.Join();
Thread 類是 .NET 多線程的基石,理解其生命週期、同步原語、線程池關係至關重要。新專案優先考慮 Task 與 async/await,僅在需要精確控制線程身分(如 COM STA、專用線程名、實時性)時直接使用 Thread。