c#线程池要如何实现?java扩展

TheDisguiser 2020-05-25 21:23:06 java常见问答 8714

上回我们说到了java中如何实现线程池及它的原理,这次我们就来看看在C#中要如何实现线程池,快来一起看看吧。

线程池简单实现

通常来讲,一个简单的线程池至少会包含下面的这些部分:

1)、线程池管理器(ThreadPoolManager):用来创建,并管理线程池

2)、工作线程(WorkThread):线程池中线程

3)、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行。

4)、任务队列:用来存放没有处理的任务。

提供了一种缓冲机制。

下面我们通过一个最简单的线程池实现来看看线程池的工作过程吧:

线程池创建

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
namespace ThreadManager
{
    public class ThreadPoolManager
    {
        private int MaxThreadNum;
        private int MinThreadNum;
        private int GrowStepNum;
        //线程数量
        public int ThreadNum
        {
            get;
            set;
        }
        //默认线程数量
        public int DefaultThreadNum
        {
            get;
            set;
        }
        private Queue < Task > TaskQueue;
        private Queue < WorkThread > WorkThreadList;
        public ThreadPoolManager(int i)
        {
            TaskQueue = new Queue < Task > ();
            WorkThreadList = new Queue < WorkThread > ();
            DefaultThreadNum = 10;
            if (i > 0)
                DefaultThreadNum = i;
            CreateThreadPool(i);
        }
        public ThreadPoolManager(): this(10)
        {}
        public bool IsAllTaskFinish()
        {
            return TaskQueue.Count == 0;
        }
        public void CreateThreadPool(int i)
        {
            if (WorkThreadList == null)
                WorkThreadList = new Queue < WorkThread > ();
            lock(WorkThreadList)
            {
                for (int j = 0; j < i; j++)
                {
                    ThreadNum++;
                    WorkThread workthread = new WorkThread(ref TaskQueue, ThreadNum);
                    WorkThreadList.Enqueue(workthread);
                }
            }
        }
        public void AddTask(Task task)
        {
            if (task == null)
                return;
            lock(TaskQueue)
            {
                TaskQueue.Enqueue(task);
            }
            //Monitor.Enter(TaskQueue);
            //TaskQueue.Enqueue(task);
            //Monitor.Exit(TaskQueue);
        }
        public void CloseThread()
        {
            //Object obj = null;
            while (WorkThreadList.Count != 0)
            {
                try
                {
                    WorkThread workthread = WorkThreadList.Dequeue();
                    workthread.CloseThread();
                    continue;
                }
                catch (Exception)
                {}
                break;
            }
        }
    }
}

工作线程类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadManager
{
    public class WorkThread
    {
        public int ThreadNum
        {
            get;
            set;
        }
        private bool flag;
        private Queue < Task > TaskQueue;
        private Task task;
        public WorkThread(ref Queue < Task > queue, int i)
        {
            this.TaskQueue = queue;
            ThreadNum = i;
            flag = true;
            new Thread(run)
                .Start();
        }
        public void run()
        {
            while (flag && TaskQueue != null)
            {
                //获取任务
                lock(TaskQueue)
                {
                    try
                    {
                        task = TaskQueue.Dequeue();
                    }
                    catch (Exception)
                    {
                        task = null;
                    }
                    if (task == null)
                        continue;
                }
                try
                {
                    task.SetEnd(false);
                    task.StartTask();
                }
                catch (Exception)
                {}
                try
                {
                    if (!task.IsEnd())
                    {
                        task.SetEnd(false);
                        task.EndTask();
                    }
                }
                catch (Exception)
                {}
            } //end of while
        }
        public void CloseThread()
        {
            flag = false;
            try
            {
                if (task != null)
                    task.EndTask();
            }
            catch (Exception)
            {}
        }
    }
}

Task类与实现类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ThreadManager
{
    public interface Task
    {
        /// <summary>
        /// set flag of task.
        /// </summary>
        void SetEnd(bool flag);
        /// <summary>
        /// start task.
        /// </summary>
        void StartTask();
        /// <summary>
        /// end task.
        /// </summary>
        void EndTask();
        /// <summary>
        /// get status of task.
        /// </summary>
        /// <returns></returns>
        bool IsEnd();
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadManager
{
    public class TestTask: Task
    {
        private bool is_end;
        public void SetEnd(bool flag)
        {
            is_end = flag;
        }
        public void StartTask()
        {
            Run();
        }
        public void EndTask()
        {
            is_end = true;
            Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":" + "结束!");
        }
        public bool IsEnd()
        {
            return is_end;
        }
        public void Run()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":" + i);
            }
        }
    }
}

这就是如何在C#中创建一个简单的线程池了,你明白了吗?如果想要了解更多线程池相关java常见问答知识,就请关注我们的网站吧。

推荐阅读:

四种线程池分别都有哪些原理?要怎么实现?

线程池有几种?线程池的种类案列

创建线程池该如何创建?有几种方式?