代码改变世界

多线程调用本质

2013-01-08 23:12  hongjiumu  阅读(458)  评论(0编辑  收藏  举报

System.Threading.Thread.Sleep(0)
和System.Threading.Thread.Sleep(100)
100 是线程阻塞的毫秒数,表示0.1 秒,在阻塞时线程状态是 ThreadState.WaitSleepJoin
指定0 以指示应挂起此线程以使其他等待线程先执行

public abstract class Framework
    {
        private static bool _vbSuccess = false;
        private int _viIndex = 0;
 
        public abstract void Perform();
 
        public void Start()
        {
            Monitor();
            while(_vbSuccess)
                System.Threading.Thread.Sleep(0);
            Console.WriteLine("Result:{0}",_viIndex);
            Perform();
        }
 
        private void Monitor()
        {
            _vbSuccess = true;
            System.Threading.Thread thread
                = new System.Threading.Thread(DoWork);
            thread.IsBackground = true;
            thread.Name = "WT # " + DateTime.Now;
            thread.Start();
        }
 
        private void DoWork()
        {
            for (int i = 0; i < 1234567;i++ )
            {
                _viIndex = i;
                if (i % 99 == 0)
                    Console.WriteLine("Current:{0}",i);
            }
            _vbSuccess = false;
        }
 
    }
public class Work:Framework
{
    public Work()
    {
        Start();
    }
 
    public override void Perform()
    {
        Console.WriteLine("Hello");
    }
}
 
 
class Program
{
    static void Main(string[] args)
    {
        Work vWork = new Work();
        Console.WriteLine("Over");
        Console.Read();
    }
}