基本的 Thread 框架
基本的 Thread 程序结构,由工作函数,start 和 join 组成
Thread类是比较常用的一个类,这里总结了一些基本的使用方法和程序示例,以备以后查用。
https://msdn.microsoft.com/zh-cn/library/system.threading.thread.aspx
using System;
using System.Threading;
// Simple threading scenario: Start a static method running
// on a second thread.
public class ThreadExample
{
// The ThreadProc method is called when the thread starts.
// It loops ten times, writing to the console and yielding
// the rest of its time slice each time, and then ends.
public static void ThreadProcA()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadProc A: {0}", i);
Thread.Sleep(0);
}
}
public static void ThreadProcB()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("ThreadProc B: {0}", i);
// Yield the rest of the time slice.
Thread.Sleep(0);
}
}
public static void Main()
{
Console.WriteLine("Main thread: Start a second thread.");
// The constructor for the Thread class requires a ThreadStart
// delegate that represents the method to be executed on the
// thread. C# simplifies the creation of this delegate.
Thread t = new Thread(new ThreadStart(ThreadProcA));
Thread t1 = new Thread(new ThreadStart(ThreadProcB));
// Start ThreadProc. Note that on a uniprocessor, the new
// thread does not get any processor time until the main thread
// is preempted or yields. Uncomment the Thread.Sleep that
// follows t.Start() to see the difference.
t.Start();
t1.Start();
//Thread.Sleep(0);
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Main thread: Do some work.");
Thread.Sleep(0);
}
Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
t.Join();
t1.Join();
Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program.\n");
Console.ReadLine();
}
}
这仅仅是一个创建两个线程的例子,但并不太符合实际应用的情况 此时的输出结果A 与 B 随机打印。