• C#学习Thread


          .NET框架是C#的运行时类库,.NET是一个多线程的环境。线程(Thread)是进程中一个单一的顺序控制流程。线程是进程中的实体。一个进程可以有多个线程,一个线程必须有一个父进程。

         线程一般具有read,blocking和operation三种基本状态。由三种基本状态,衍化出五种线程的基本操作。首先,derive,线程是在进程内派生出来的。其次,schedule,选择一个ready的线程进入operation状态。第三,block,如果一个线程在执行过程中需要等待某个事件发生则被阻塞。第四,unblock,如果事件开始,则该线程被unblock,进入ready队列。第五,finish,线程结束,它执行过的寄存器上下文及堆栈内容会被释放。

         新线程是新产生的线程对象,它还没有分配资源。因此只能用start()或close()方法。

         Runable状态就是线程在start()方法运行后,得到线程所必需资源并且调用run()方法执行。

         Not Runable非运行状态是发生以下事件而进入的状态,suspend()方法被调用,sleep()方法被调用,线程使用wait()来等待条件变量,线程处于I/O等待。

        Dead是当Run()方法返回,或别的线程调用stop()方法,线程进入Dead状态。下边是Thread的两个简单例子。

    Using System;
    using  System.Threading;
    public class SimpleThread
    {
         public void Method()
         {
              int i = 1,j = 2;
              int result = i + j ;
              Console.WriteLine("thread{0} Value{1}",
              AppDomain.GetCurrentThreadId().ToString,
              result.ToString());
         }  
         static void Main()
         {
              SimpleThread thread1 = new SimpleThread();
              thread1.Method();
              ThreadStart ts = new ThreadStart(thread1.Method);
              Thread t = new Thread(ts);
              t.Start();
              Console.ReadLine();
          }
    }
     1 using System;
     2 using System.Threading;
     3 
     4 public class ThreadExample
     5 {
     6        public static void ThreadProc()
     7        {
     8               for(int i = 0; i <10; i++)
     9               {
    10                   Console.WriteLine("ThreadProc:{0}",i);
    11                   Thread.Sleep(0);
    12               }
    13         }
    14         public static void Main()
    15         {
    16                Console.WriteLine("Main thread: Start a second thread.");
    17                Thread t =new Thread(new ThreadStart(ThreadProc));
    18                t.Start();
    19                for(int i = 0; i < 4; i++)
    20                {
    21                     Console.WriteLine("Main thread:Do some work.");
    22                     Thread.Sleep(0);
    23                }
    24                 Console.WriteLine("Main thread:Call Join(),to wait until ThreadProc ends.");
    25                 t.Join();
    26                 Console.WriteLine(Main thread:ThreadProc.Join has returned.Press Enter to end program.");
    27                 Console.ReadLine();
    28          }
    29 } 
  • 相关阅读:
    九、分布式事务
    L2008 最长对称子串
    L2004 这是二叉搜索树吗?
    L2001 紧急救援
    L2003 月饼
    L2007 家庭房产
    L2006 树的遍历
    L2009 抢红包
    L2005 集合相似度
    L2002 链表去重
  • 原文地址:https://www.cnblogs.com/virgil/p/2675212.html
Copyright © 2020-2023  润新知