zoukankan      html  css  js  c++  java
  • 多线程按顺序执行

    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!"); } } }

      

    
    

      

  • 相关阅读:
    C#微信开发文档
    XML相关操作
    css基本样式总结
    CSS选择器及其优先级
    Java学习之路(七)
    G2( bizCharts ) React 绘制混合图例
    G2 绘制混合图例 demo
    python 前后端分离 简单的数据库返回接口
    nginx 跨域
    react-router-dom
  • 原文地址:https://www.cnblogs.com/hirisw/p/2388900.html
Copyright © 2011-2022 走看看