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