线程基础之创建,暂停,等待,锁

 1 using System;
 2 using System.Threading;
 3 using static System.Console;//语法糖 使用static #6.0特性 让我们可以访问类型的静态成员
 4  
 5 
 6 namespace Chapter1.Recipe1
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //1.创建线程,执行循环打印DelayPrint()
13             //2.之后立马执行PrintNumber()
14             //3.但是 DelayPrint() 加入了Sleep 使线程处在休眠状态  占用CPU时间少 所以会先执行PrintNumbers() 
15             Thread t = new Thread(DelayPrint);
16             t.Start();//Start:线程开始
17             PrintNumbers();
18 
19 
20             //加入Join就避免了先执行PrintNumbers方法 DelayPrint没打印完成之前 Main不会往下走
21             Thread t1 = new Thread(DelayPrint);
22             t1.Start();//Start:线程开始
23             t1.Join();//Join:线程等待
24             PrintNumbers();
25         }
26       
27         static void PrintNumbers()
28         {
29             WriteLine("Starting1...");
30             for (int i = 1; i < 10; i++)
31             {  //循环打印输入1-10
32                 WriteLine(i);
33             }
34         }
35         //延迟打印
36         static void DelayPrint()
37         {
38             WriteLine("Starting2...");
39             for (int i = 0; i <= 10; i++)
40             {
41                 Thread.Sleep(TimeSpan.FromSeconds(2));//线程暂停
42                 WriteLine(i);
43             }
44         }
45     }
46 }
线程创建,等待,查看
using System;
using System.Threading;
using static System.Console;
using static System.Threading.Thread;

namespace Chapter1.Recipe5
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Starting program 开始程序...");
            Thread t = new Thread(PrintNumbersWithStatus);//创建线程t 打印当前线程状态
    
            t.Start();
        
        
            for (int i = 1; i < 100; i++)
            {//在执行 Sleep之前县城是Running运行状态 执执行之后就可以获取到线程处于WaitSleepJoin等待状态
                WriteLine(t.ThreadState.ToString());
            }
        
             
            WriteLine("A thread has been aborted 这个线程是已经终止的");
            WriteLine(t.ThreadState.ToString()+"最后1");
        
        }

        
        //打印第几个线程状态状态
        static void PrintNumbersWithStatus()
        {
            WriteLine("Starting...开始");
            WriteLine(CurrentThread.ThreadState.ToString());
            for (int i = 1; i < 10; i++)
            {
                Sleep(TimeSpan.FromSeconds(2));
                WriteLine(i);
            }
        }
    }
}
查看当前线程状态
using System;
using System.Threading;
using static System.Console;
using static System.Threading.Thread;
using static System.Diagnostics.Process;

namespace Chapter1.Recipe6
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine($"Current thread priority 当前线程优先级: {CurrentThread.Priority}");
        
            RunThreads();
            Sleep(TimeSpan.FromSeconds(2));
            WriteLine("Running on a single core在单个CPU上运行");
            GetCurrentProcess().ProcessorAffinity = new IntPtr(1);//让操作系统运行在单个CPU上 得到优先级或高的线程会计算更多
            RunThreads();
        }
        //执行两个线程 设置优先级并让他们各自迭代 两秒后暂停所有线程并得到迭代数字
        static void RunThreads()
        {
            var sample = new ThreadSample();

            var threadOne = new Thread(sample.CountNumbers);
            threadOne.Name = "ThreadOne";
            var threadTwo = new Thread(sample.CountNumbers);
            threadTwo.Name = "ThreadTwo";

            threadOne.Priority = ThreadPriority.Highest;  

            threadTwo.Priority = ThreadPriority.Lowest;
            threadOne.Start();
            threadTwo.Start();

            Sleep(TimeSpan.FromSeconds(2));
            sample.Stop();
        }

        class ThreadSample
        {
            private bool _isStopped = false;

            public void Stop()
            {
                _isStopped = true;
            }

            public void CountNumbers()
            {
                long counter = 0;

                while (!_isStopped)
                {
                    counter++;
                }

                WriteLine($"{CurrentThread.Name} with " +
                    $"{CurrentThread.Priority,11} priority " +
                    $"has a count = {counter,13:N0}");
            }
        }
    }
}
线程优先级,在单核下优先级越高CPU给他的时间更多

 

1:为什么要使用锁(Lock):

  1,多个线程共享一个资源,必须保证当前线程使用该资源的时候,所以其他线程需要等待当前线程完成操作

  2,使用Lock来实现这种行为,但是使用之后其他线程将会处于阻塞状态,这也会带来性能问题,

  3,lock其实就是Monitor类的一个语法糖

  4,使用try/catch块的时候 不要在线程外捕获异常,捕获不到, 应该在编写线程的代码块中捕获异常

你可能感兴趣的:(线程基础之创建,暂停,等待,锁)