• 多线程按顺序执行


    using System;
    using System.Collections.Generic;
    using System.Threading;
    
    namespace _3vjDemos
    {
    //实现类: [Serializable] public class OrderedExecuteThread { public OrderedExecuteThread ThreadFront { get; set; } [System.Xml.Serialization.XmlIgnore] public Action<Object> ActionDoing { get; set; } [System.Xml.Serialization.XmlIgnore] public Thread Thread { get; set; } public bool IsCurrentExcuted { get; set; } public bool IsCurrentStarted { get; set; } public bool IsCurrentDealt { get; set; } public int OrderedIndex { get; set; } public void ExecuteThread(Object obj) { try { Thread.Sleep(new Random().Next(0, 200) * 100); while (true) { if ((ThreadFront == null || ThreadFront.Thread == null || ThreadFront.IsCurrentExcuted) && !this.IsCurrentExcuted&&!IsCurrentStarted) { Thread.Start(this.OrderedIndex); this.IsCurrentStarted = true; } Thread.Sleep(50); if (!Thread.IsAlive && IsCurrentStarted) { this.IsCurrentExcuted = true; break; } } IsCurrentDealt = true; if (ActionDoing != null) { ActionDoing.Invoke(obj);//DoSomeThing } } catch (Exception ex) { Console.WriteLine("Thread " + this.OrderedIndex.ToString() + " exit by " + ex.Message); } } } //测试类: public class OrderedExecuteThreads { public List<OrderedExecuteThread> OrderedThreads { get; set; } public void ExecuteThreads() { for (int i = OrderedThreads.Count - 1; i >= 0; i--) { var thread = OrderedThreads[i]; if (!thread.IsCurrentDealt) { Thread tTest = new Thread(thread.ExecuteThread); tTest.Start(null); } } } public static void OrderedExecuteThreadTest(int threadCount) { List<OrderedExecuteThread> orderedThreads = new List<OrderedExecuteThread>(); List<Thread> threads = new List<Thread>(); for (int i = 0; i < threadCount; i++) { Thread thread = new Thread(new ParameterizedThreadStart(PrintExecuteThreadIndex)); threads.Add(thread); } for (int i = 0; i < threadCount; i++) { OrderedExecuteThread orderThread = new OrderedExecuteThread(); orderThread.Thread = threads[i]; orderThread.OrderedIndex = i; orderedThreads.Add(orderThread); } for (int i = 0; i < threadCount; i++) { OrderedExecuteThread orderThread = orderedThreads[i]; if (i > 0) { orderThread.ThreadFront = orderedThreads[i - 1]; } } OrderedExecuteThreads executeThreads = new OrderedExecuteThreads(); executeThreads.OrderedThreads = orderedThreads; executeThreads.ExecuteThreads(); } private static void PrintExecuteThreadIndex(object index) { Console.WriteLine("Thread " + index.ToString() + " executed!"); } } }

      

    
    

      

  • 相关阅读:
    利用Abot爬虫和visjs 呈现漫威宇宙
    Abot 爬虫分析-整体结构
    利用Abot 抓取博客园新闻数据
    sftp配置多个用户权限的问题
    十三、Vue中的computed属性
    十二、react-reudx之@connect 摆脱redux的繁琐操作
    十一、微信小程序-var、let、const用法详解
    十、es6之扩展运算符 三个点(...)
    九、小程序 Redux详解与在小程序中怎么使用(action和reducers)
    八、wepy代码规范
  • 原文地址:https://www.cnblogs.com/hirisw/p/2388900.html
Copyright © 2020-2023  润新知