zoukankan      html  css  js  c++  java
  • c# 多线程概览

    场景:1~1000累加求和

    只考虑如何启用多线程计算,不考虑线程同步

    实现方式:

    1.Thread thread=new Thread(new ThreadStart(some delegate)); 无参数启动新线程。

    2.Thread thread=new Thread(new ParameterizedThreadStart(some delegate,params)); 带参数启动新线程。

    3.将线程操作封装为一个独立方法,其中使用匿名方法的方式将外部参数导入。

    4.ThreadPool.QueueUserWorkItem(delegeate,params)带参数的线程池方法,

        注意线程池中分配的线程都是background线程,主线程终止会导致子线程终止。

    5.Task,都多重方式,底层使用的Threadpool,需要使用wait方法阻塞主线程。

    6.构造一个包含参数、操作的类,通过类的属性将参数传递给操作。

    7.通过委托的方式,可以传参,并且可以有返回值。

    以上除了委托方式,其他可以传参的方式,都可以通过把返回值封装在参入参数中,使用引用的方式获得返回值。

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace multithreadTest
    {
        class Program
        {
            static Stopwatch watch = new Stopwatch();
            static int length = 100;
            static int count;
            static void Main(string[] args)
            {
                
                Console.WriteLine("Main Thread:{0}", Thread.CurrentThread.ManagedThreadId);
                //CaculateSum();
                //NoInputAndReturn();
                //MultiInputNoReturn_Anonymous();
                //MultiInputNoReturn_ParameterizedThread();
                //MultiInputNoReturn_ThreadPool();
                MultiInputNoReturn_Task();
                //MultiInputNoReturn_UseClassProperty();
                //MultiInputWithReturn_Delegate();
                Console.WriteLine("Main Thread Exit:{0}", Thread.CurrentThread.Name);
            }
    
            #region 没有输入,没有返回
            /// <summary>
            /// 没有输入,没有返回
            /// </summary>
            public static void NoInputAndReturn()
            {
                ThreadStart ts = new ThreadStart(CaculateSum);
                Thread thread=new Thread(ts);
                thread.Start();
            }
    
            /// <summary>
            /// 1~1000求和 无输入 无返回
            /// </summary>
            public static void CaculateSum()
            {
                watch.Reset();
                watch.Start();
                Console.WriteLine("IsBackground:{0}", Thread.CurrentThread.IsBackground);
                Console.WriteLine("Thread Start:{0}", Thread.CurrentThread.ManagedThreadId);
                int count = 0;
                for (var i = 0; i <= 1000; i++)
                {
                    count += i;
                    Thread.Sleep(5);
                }
                watch.Stop();
                Console.WriteLine("Thread Exit:{0},Count:{1},Time:{2}", Thread.CurrentThread.ManagedThreadId, count, watch.Elapsed);
            }
            #endregion
    
    
            #region 多输入 无返回
            #region 匿名方法
            /// <summary>
            /// 多输入 无返回 匿名方法
            /// </summary>
            public static void MultiInputNoReturn_Anonymous()
            {
                for(var i=0;i<1000;i+=(length+1))
                {
                    CaculateSum_Anonymous(i, i + length > 1000 ? 1000 : i + length);
                }
            }
    
    
            /// <summary>
            /// start~end求和 匿名方法方式
            /// </summary>
            /// <returns></returns>
            public static void CaculateSum_Anonymous(int start, int end)
            {
                Thread t = new Thread(new ThreadStart(delegate() {
                    watch.Reset();
                    watch.Start();
                    int count = 0;
                    for (var i = start; i <= end; i++)
                    {
                        count += i;
                        Thread.Sleep(5);
                    }
                    watch.Stop();
                    Console.WriteLine("Thread Exit:{0},Count:{1},Time:{2}", Thread.CurrentThread.ManagedThreadId, count, watch.Elapsed);
                }));
                t.Start();
            }
            #endregion
    
            class StartEnd
            {
                public int start;
                public int end;
            }
    
            #region ParameterizedThread包装参数
           
            public static void MultiInputNoReturn_ParameterizedThread()
            {
                for (var i = 0; i < 1000; i += (length+1))
                {
                    ParameterizedThreadStart ts = new ParameterizedThreadStart(CaculateSum_ParameterizedThread);
                    Thread thread = new Thread(ts);
                    thread.Start(new StartEnd() { start = i, end = i + length > 1000 ? 1000 : i + length });
                }
            }
    
            /// <summary>
            /// 0~end求和 一个参数 无返回
            /// </summary>
            /// <returns></returns>
            public static void CaculateSum_ParameterizedThread(object se)
            {
                watch.Reset();
                watch.Start();
                var start=((StartEnd)se).start;
                var end=((StartEnd)se).end;
                int count = 0;
                for (var i =start ; i <= end; i++)
                {
                    count += i;
                    Thread.Sleep(5);
                }
                watch.Stop();
                Console.WriteLine("Thread Exit:{0},Count:{1},Time:{2}", Thread.CurrentThread.ManagedThreadId, count, watch.Elapsed);
            }
            #endregion
    
            #region ThreadPool 包装参数
            public static void MultiInputNoReturn_ThreadPool()
            {
                for (var i = 0; i < 1000; i += (length + 1))
                {
                    ThreadPool.QueueUserWorkItem(CaculateSum_ParameterizedThread, 
                        new StartEnd() { start = i, end = i + length > 1000 ? 1000 : i + length });
                }
                
                //threadpool中的线程都是background的,如果主线程提前终止,会终止子线程的操作
                Console.WriteLine("Main thread does some work, then sleeps.");
                Thread.Sleep(5000);
    
                Console.WriteLine("Main thread exits.");
            }
            #endregion
    
            #region Task 包装参数
            public static void MultiInputNoReturn_Task()
            {
                for (var i = 0; i < 1000; i += (length + 1))
                {
                    Task t = new Task(CaculateSum_ParameterizedThread, new StartEnd() { start = i, end = i + length > 1000 ? 1000 : i + length });
                    t.Start();
                    //Task是基于线程池的,如果不使用wait会被主线程终止
                    t.Wait();
                }
                Console.WriteLine("Main thread does some work, then sleeps.");
    
                Console.WriteLine("Main thread exits.");
            }
            #endregion
    
            #region 通过类属性
            /// <summary>
            /// 多输入 无返回 通过类属性
            /// </summary>
            public static void MultiInputNoReturn_UseClassProperty()
            {
                for (var i = 0; i < 1000; i += (length+1))
                {
                    var sum = new SumTest();
                    ThreadStart start = new ThreadStart(sum.GetSum);
                    sum.Start = i;
                    sum.End = i + length > 1000 ? 1000 : i + length;
                    Thread t = new Thread(start);
                    t.Start();
                }
            }
    
            public class SumTest
            {
                public int Start;
                public int End;
    
                public void GetSum()
                {
                    watch.Reset();
                    watch.Start();
                    int count = 0;
                    for (var i = this.Start; i <= this.End; i++)
                    {
                        count += i;
                        Thread.Sleep(5);
                    }
                    watch.Stop();
                    Console.WriteLine("Thread Exit:{0},Count:{1},Time:{2}", Thread.CurrentThread.ManagedThreadId, count, watch.Elapsed);
                }
            }
    
            #endregion
            #endregion
    
            #region 传参 有返回 委托
    
            delegate TimeSpan GetSumMethod(int start, int end);
            static GetSumMethod getSum;
            public static void MultiInputWithReturn_Delegate()
            {
                int count=0;
                TimeSpan ts = new TimeSpan();
                for (var i = 0; i < 1000; i += (length+1))
                {
                    GetSumMethod getSumMethod = CaculateSum;
                    getSumMethod.BeginInvoke(i, i + length > 1000 ? 1000 : i + length,
                        new AsyncCallback(delegate(IAsyncResult result) { ts += getSumMethod.EndInvoke(result); }), null);
                }
                
                Thread.Sleep(6000);
                Console.WriteLine("TimeSpan:{0}", ts);
                Console.ReadKey();
            }
    
            public static TimeSpan CaculateSum(int start, int end)
            {
                watch.Reset();
                watch.Start();
                Console.WriteLine("Thread Start:{0}", Thread.CurrentThread.ManagedThreadId);
                int count = 0;
                for (var i = start; i <= end; i++)
                {
                    count += i;
                    Thread.Sleep(5);
                }
                watch.Stop();
                Console.WriteLine("Thread Exit:{0},Count:{1},Time:{2}", Thread.CurrentThread.ManagedThreadId, count, watch.Elapsed);
                return watch.Elapsed;
            }
    
            #endregion
    
           
        }
    }
  • 相关阅读:
    坑爹的微信支付v3,其实没有那么坑
    Mysql探究之null与not null
    Mysql的空值与NULL的区别
    Java编程思想(第4版) 中文清晰PDF完整版
    URI和URL的区别
    html 文本输入框效果大汇集
    HTTP状态码大全
    Silverlight ModelView中调用UI进程
    appium部分api
    appium元素定位
  • 原文地址:https://www.cnblogs.com/lvjianwei/p/9259527.html
Copyright © 2011-2022 走看看