C#多个线程同时执行一个任务示例

注意:如果电脑是单核单线程的,这么做是没有意义的。

这里直接贴一下主要代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Data;

namespace ThreadTest
{
    class Moultithreading
    {
        //创建2个线程
        Thread ThreadOne = new Thread(new ThreadStart(ThreadOne1));
        Thread ThreadTwo = new Thread(new ThreadStart(ThreadTwo2));
        //ListInfo用于存放待执行的任务,ListInfo2用于存放已经执行过的任务(做一个标记的作用)
        static List<string> ListInfo = new List<string>();
        static List<string> ListInfo2 = new List<string>();
        public Moultithreading()
        {
            //假定有20个待执行任务
            for (int i = 0; i < 20; i++)
            {
                ListInfo.Add(i + "");
            }
            ThreadOne.Start();
            ThreadTwo.Start();
        }
        /// <summary>
        /// 线程1执行逻辑
        /// </summary>
        private static void ThreadOne1()
        {
            ThreadExecute("One");
        }
        /// <summary>
        /// 线程2执行逻辑,与线程1相同
        /// </summary>
        private static void ThreadTwo2() 
        {
            ThreadExecute("Two");
        }
        /// <summary>
        /// 线程执行任务的通用方法,这里因为2个线程执行逻辑相同,就写到一起了。用一个参数加以区分
        /// </summary>
        /// <param name="ThreadNum"></param>
        private static void ThreadExecute(string ThreadNum)
        {
            for (int i = 0; i < ListInfo.Count; i++)
            {
                try
                {
                    //当前任务未执行过,且未被其他线程占用
                    if (!ListInfo2.Contains(ListInfo[i]) && Monitor.TryEnter(ListInfo[i], 1000))
                    {
                        Console.WriteLine("线程" + ThreadNum + "执行了任务:" + ListInfo[i]);//执行任务
                        ListInfo2.Add(ListInfo[i]);//任务执行完添加标记
                        Thread.Sleep(400);
                    }
                }
                finally
                {
                    if (Monitor.TryEnter(ListInfo[i]))
                    {
                        Monitor.Exit(ListInfo[i]);//释放锁
                    }
                }
            }
        }
    }
}
执行结果:

posted on 2018-07-11 17:08  水为痕  阅读(8896)  评论(0编辑  收藏  举报

导航