多线程5.0第一章

1、实现

        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumbers);
            thread.Start();
            PrintNumbers();
            Console.Read();
        }

        static void PrintNumbers()
        {
            Console.WriteLine("starting");
            for (var i = 0; i < 100; i++)
            {
                Console.WriteLine(i);
            }
        }
View Code

2、暂停线程:Thread.Sleep(),让线程等待一段时间而不消耗操作系统资源

        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumbersWithDelay);
            thread.Start();
            PrintNumbers();
            Console.Read();
        }

        static void PrintNumbers()
        {
            Console.WriteLine("Starting...");
            for (var i = 0; i < 10; i++)
            {
                Console.WriteLine(i);
            }
        }

        static void PrintNumbersWithDelay()
        {
            Console.WriteLine("Starting...");
            for (var i = 0; i < 10; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine(i);
            }
        }
View Code

3、线程等待:Thread.Join(),让程序等待另一线程计算完成,因为不知道要多少时间,所以Thread.Sleep()不行

        static void Main(string[] args)
        {
            Thread thread = new Thread(PrintNumbersWithDelay);
            thread.Start();
            thread.Join();
            Console.WriteLine("Thread completed");
            Console.Read();
        }

        static void PrintNumbersWithDelay()
        {
            Console.WriteLine("Starting...");
            for (var i = 0; i < 10; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine(i);
            }
        }
View Code

4、线程终止:Thread.Abort(),相当于给子线程注入一个ThreadAbortException方法,导致线程终止。但是这是非常危险的,因为该异常可以在任何时刻发生并可能彻底摧毁应用程序。另外子线程也可以通过Thread.ResetAbort()来拒绝线程终止,所以不推荐用Thread.Abort来关闭线程,可以优先使用其他方法,如提供一个CancellationToken方法来取消线程的执行。

        static void Main(string[] args)
        {
            Console.WriteLine("Starting Program...");
            Thread thread = new Thread(PrintNumbersWithDelay);
            thread.Start();
            Thread.Sleep(TimeSpan.FromSeconds(6));
            thread.Abort();
            Console.WriteLine("A thread has been aborted");
            Console.Read();
        }

        static void PrintNumbersWithDelay()
        {
            try
            {
                Console.WriteLine("Starting...");
                for (var i = 0; i < 10; i++)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(2));
                    Console.WriteLine(i);
                }
            }
            catch (ThreadAbortException e)
            {
                Console.WriteLine(e.ExceptionState);
                Thread.ResetAbort();
            }
            finally
            {
                Console.WriteLine("Do something else in finally{}.");
            }
            Console.WriteLine("Do something else here.");
        }
View Code

5、线程状态

        static void Main(string[] args)
        {
            Console.WriteLine("Starting Program...");
            Thread thread = new Thread(PrintNumbersWithStatus);
            Console.WriteLine(thread.ThreadState.ToString());
            thread.Start();
            for (int i = 1; i < 3; i++)
            {
                Console.WriteLine(thread.ThreadState.ToString());
            }
            Thread.Sleep(TimeSpan.FromSeconds(6));
            thread.Abort();
            Console.WriteLine("A thread has been aborted");
            Console.WriteLine(thread.ThreadState.ToString());
            Console.Read();
        }

        static void PrintNumbersWithStatus()
        {
            Console.WriteLine(Thread.CurrentThread.ThreadState.ToString());
            for (var i = 0; i < 10; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine(i);
            }
        }
View Code

 6、线程优先级,如果是多核,优先级高的执行多一点,优先级低的执行少一点,但是两个值应该接近。Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);让所有线程运行在单个cpu核心上,优先级高的远超于优先级低的。

class Program
    {
        
        static void Main(string[] args)
        {
            Console.WriteLine("Current thread priority:{0}", Thread.CurrentThread.Priority);
            Console.WriteLine("Running on all cores available");
            RunThreads();
            Thread.Sleep(TimeSpan.FromSeconds(2));
            Console.WriteLine("Running on a single core");
            Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
            RunThreads();
            Console.Read();
        }

        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();

            Thread.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++;
            }
            Console.WriteLine("{0} with{1,11} priority has a count ={2,13}", Thread.CurrentThread.Name, 
                Thread.CurrentThread.Priority, counter.ToString("N0"));
        }
    }
View Code

 7、前台线程和后台线程:如果前台线程不结束,主线程不会正常结束。但是后台线程不结束,主线程可以结束。

class Program
    {
        
        static void Main(string[] args)
        {
            var sampleForeground = new ThreadSample(10);
            var sampleBackground = new ThreadSample(20);

            var threadOne = new Thread(sampleForeground.CountNumbers);
            threadOne.Name = "ForegroundThread";
            var threadTwo = new Thread(sampleBackground.CountNumbers);
            threadTwo.Name = "BackgroundThread";
            threadTwo.IsBackground = true;

            threadOne.Start();
            threadTwo.Start();
        }
    }

    class ThreadSample
    {
        private readonly int _iterations;
        public ThreadSample(int iterations)
        {
            _iterations = iterations;
        }
        public void CountNumbers()
        {
            for(int i=0;i<_iterations;i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
            }
        }
    }
View Code

 8、线程参数:参考https://www.cnblogs.com/a924453846/articles/4602154.html

posted @ 2022-01-20 11:32  江境纣州  阅读(21)  评论(0编辑  收藏  举报