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

      

    
    

      

  • 相关阅读:
    【博客申明】
    OAF客制化代码导出页面数据到Excel文件
    OAF调用JS代码
    Java冒泡排序
    Java二分查找代码
    Java 在某一个时间点定时执行任务(转载)
    Oracle 常用SQL
    Oracle数据字典
    spring3.0事务管理配置
    由override 和 overload 引发的学习感悟
  • 原文地址:https://www.cnblogs.com/hirisw/p/2388900.html
Copyright © 2011-2022 走看看