1、一些Thread基本理论
一个进程可以创建一个或多个线程以执行与该进程关联的部分程序代码。使用 委托或 委托指定由线程执行的程序代码。使用 委托可以将数据传递到线程过程。
在线程存在期间,它总是处于由 定义的一个或多个状态中。可以为线程请求由 定义的调度优先级,但不能保证操作系统会接受该优先级。
提供托管线程的标识。在线程的生存期内,无论获取该值的应用程序域如何,它都不会和任何来自其他线程的值冲突。
2、案例代码分析
在主线程中调用其它线程,执行的过程有取决于操作系统的调度及时间的分配。
图1,t.join()开启时,调用t的主线程main主线程会被阻塞,等待t线程执行完才去执行最后一句控制台输出;
图2,t.join()关闭,调用t的主线程main主线程会不会阻塞,执行最后一台控制台输出完全不受T线程限制,没等t线程执行完就输出了;
图3,t.start()后加了一个Thread.sleep(1),使main主线程休眠1秒(期间t线程照常执行)。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace Threaddeom
- {
- ///
- /// 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 ThreadProc()
- {
- for (int i = 0; i < 10; i++)
- {
- Console.WriteLine("ThreadProc: {0}", i);
- /* Yield the rest of the time slice. */
- Thread.Sleep(0);
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- while (true)
- {
- 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(ThreadProc));
- /*
- * 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();
- /* 通过Thread.Sleep可以让主线程休眠,从而优先完次线程的内容 */
- //Thread.Sleep(1);
- 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();
- Console.WriteLine("Main thread: ThreadProc.Join has returned. Press Enter to end program.");
- Console.ReadLine();
- Console.Clear();
- }
- }
- }
- }
- }
图1 join开启
图2 join关闭
图3 Thread.sleep(1)开启
4、源工程代码
Threaddemo.rar
阅读(1897) | 评论(0) | 转发(0) |