C#多线程的用法1-简单示例

写在前面:阅读本系列文章即表示你已经知道什么是线程等理论知识,现在正想了解如何正确的使用线程进行编程工作。

/// <summary>
/// 单线程工作示例
/// </summary>
private static void SingleThreadDemo()
{
Console.WriteLine("Main Thread");
Thread thread = new Thread(() =>
{
for (var i = 0; i < 10; i++)
{
Console.WriteLine(String.Format("Thread Out:{0}", i));
Thread.Sleep(500);
}
Console.WriteLine("Sub Thread The End");
});
thread.Start();
Console.WriteLine("Main Thread Wait For Sub Thread");
}
/// <summary>
/// 多个线程工作示例
/// </summary>
private static void MultiThreadDemo()
{
ThreadStart task = () =>
{
for (var i = 0; i < 10; i++)
{
Console.WriteLine(String.Format("Thread {0} Out:{1}", Thread.CurrentThread.Name, i));
Thread.Sleep(500);
}
Console.WriteLine(String.Format("Sub Thread {0} The End", Thread.CurrentThread.Name));
};
Console.WriteLine("Main Thread");
Thread thread1 = new Thread(task)
{
Name = "thread1"
};
thread1.Start();
Thread thread2 = new Thread(task)
{
Name = "thread2"
};
thread2.Start();
Thread thread3 = new Thread(task)
{
Name = "thread3"
};
thread3.Start();
Console.WriteLine("Main Thread Wait For Sub Thread");
} static void Main(string[] args)
{
//SingleThreadDemo();
//MultiThreadDemo();
Console.ReadLine();
}

  

上一篇:C,C++经典(程序、错误程序)


下一篇:5.PHP 教程_PHP echo/print