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);
        }
    }
  • 相关阅读:
    定时发布测试,没有内容,不要看了,定明天九点发布,看行不
    四十个非常实用的轻量级JavaScript库
    手把手教你用杰奇建小说站
    IIS与Apache共用80端口方法
    jQuery循环滚动展示代码
    分享二十五个不错的下拉菜单导航JS脚本
    以信用卡还信用卡财付通
    codesmith 如何把选中的多个表生成实体
    从零开始学习jQuery 让页面动起来!
    10 个提供免费域名搜索建议服务的网站
  • 原文地址:https://www.cnblogs.com/luyinghuai/p/1277110.html
Copyright © 2011-2022 走看看