• 多线程按顺序执行


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

      

    
    

      

  • 相关阅读:
    xargs命令
    grep命令详细解析 --非原创 原作者ggjucheng
    centos如何安装Python3
    Custom Draw 基础(转载)
    Make 命令教程(转载)
    选择Blobs (Evision)
    图像预处理(Evision)
    一个野生程序员开博日
    Ubuntu 14.04 apt源更新
    python核心编程3-13
  • 原文地址:https://www.cnblogs.com/hirisw/p/2388900.html
Copyright © 2020-2023  润新知