日期:2014-05-18 浏览次数:21008 次
using System; using System.Threading; namespace 一个对象一个线程 { class Program { static void Main(string[] args) { var t1 = new MyClass {WaitTime = 1000}; var t2 = new MyClass { WaitTime = 6000 }; int i = 0; while (true) { var curr=new MyClass(); if (i++ % 2 == 0) { Execute(t1); } else { curr = t2; var thread = new Thread(new ParameterizedThreadStart(Execute)); Console.WriteLine("开始新线程id:" + thread.ManagedThreadId); thread.Start(t2); } Thread.Sleep(1000); } } static void Execute(object obj) { var me = (MyClass) obj; if (me.WaitTime == 1000) { Console.WriteLine("开始执行"); Thread.Sleep(me.WaitTime); Console.WriteLine("执行完毕"); } else { { Console.WriteLine("-------------------开始执行"); Thread.Sleep(me.WaitTime); Console.WriteLine("-------------------执行完毕"); } } } } class MyClass { public int WaitTime { get; set; } } }
static void Main(string[] args) { var t1 = new MyClass {WaitTime = 1000}; var t2 = new MyClass { WaitTime = 6000 }; int i = 0; while (true) { var curr=new MyClass(); if (i++ % 2 == 0) { Execute(t1); } else { curr = t2; if (!curr.IsRun) { var thread = new Thread(new ParameterizedThreadStart(Execute)); Console.WriteLine("开始新线程id:" + thread.ManagedThreadId); thread.Start(t2); } } Thread.Sleep(1000); } } static void Execute(object obj) { var me = (MyClass) obj; me.IsRun = true; if (me.WaitTime == 1000) { Console.WriteLine("开始执行"); Thread.Sleep(me.WaitTime); Console.WriteLine("执行完毕"); } else { { Console.WriteLine("-------------------开始执行"); Thread.Sleep(me.WaitTime); Console.WriteLine("-------------------执行完毕"); } } me.IsRun = false; } } class MyClass { public int WaitTime { get; set; } private bool _isrun = false; public bool IsRun { get { return this._isrun; } set { this._isrun = value; } } }