zoukankan      html  css  js  c++  java
  • 分别用线程池和List实现同样的功能

    Threadpool线程池和泛型List<Thread>,实现同样功能的多线程的例子。

    下载原代码 

    Code:

    using System;
    using System.Threading;
    using System.Collections.Generic;
    public class OprateClass
    {
        
    public OprateClass( ManualResetEvent doneEvent)
        {
            _doneEvent 
    = doneEvent;
        }

        
    // Wrapper method for use with thread pool.
        public void ThreadPoolCallback(Object threadContext)
        {
            
    int threadIndex = (int)threadContext;
            Console.WriteLine(
    "Thread parameter:{0}", threadIndex);
            
            _doneEvent.Set();
        }

        
    private ManualResetEvent _doneEvent;
    }

    public class ThreadPoolExample
    {
        
    static void Main()
        {
            
    //1:the way used threadpool
            const int iCount = 10;
            
    // One event is used for each object
            ManualResetEvent[] doneEvents = new ManualResetEvent[iCount];

            
    // Configure and launch threads using ThreadPool:
            Console.WriteLine("launching {0} tasks", iCount);
            
    for (int i = 0; i < iCount; i++)
            {
                doneEvents[i] 
    = new ManualResetEvent(false);
                OprateClass f 
    = new OprateClass(doneEvents[i]);
                ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
            }

            
    // Wait for all threads in pool to calculation
            WaitHandle.WaitAll(doneEvents);
            Console.WriteLine(
    "All calculations are complete.");

            
    //2:the way used thread list,if need
            
            List
    <Thread> ilistThread = new List<Thread>();
            
            
    //the method which no paramaters
            
    //ThreadStart idele = new ThreadStart(test);
            
    //have parameters
            ParameterizedThreadStart idele = new ParameterizedThreadStart(test);

            Thread ithread 
    = null;
            
    for (int i = 0; i < 10; i++)
            {
                ithread 
    = new Thread(idele);
                ithread.Start(i);
                ilistThread.Add(ithread);
            }

            
    //wait all of thread finish
            foreach (Thread ith in ilistThread)
            {
                ith.Join();
            }
            
            Console.WriteLine(
    "done");
            
        }

        
    static void test(object i)
        {
            Console.WriteLine(i);
            Thread.Sleep(
    20000);
        }
    }
  • 相关阅读:
    2020软件工程第三次作业
    2020软件工程作业02
    2020软件工程作业01
    2020软件工程个人作业06——软件工程实践总结作业
    2020软件工程作业05
    2020软件工程作业00——问题清单
    2020软件工程作业04
    2020软件工程作业03
    2020软件工程作业02
    2020软件工程作业01
  • 原文地址:https://www.cnblogs.com/luyinghuai/p/1277110.html
Copyright © 2011-2022 走看看