代码改变世界

c#多线程(一)

2009-12-10 23:17  c#在路上  阅读(840)  评论(0)    收藏  举报

对于线程操作,一直没有特别的会用。自己写了些代码:贴出来大家分享。

代码

        
#region 简单线程,主线程与子线程threadAnther,局部变量互不影响

        
static void SilmpleMultThread()
        {
            Thread threadAnther 
= new Thread(new ThreadStart(WrietConsole));
            threadAnther.Start();
//新线程启动,
            while (true) Console.Write("Y");//主线程不停的写 “Y”
        }

        
static void WrietConsole()
        {
            
while(true) Console.Write("X");//不停的写“X”
        }
        
#endregion

        
#region 副本分别在各自的内存堆栈中创建

        
static void SimpleShareMultThread()
        {
            
//变量x的副本分别在各自的内存堆栈中创建,输出也一样;
            Thread threadAnther = new Thread(new ThreadStart(Go));
            threadAnther.Start();
            Go();
        }

        
static void Go()
        {
            
//声明和使用同一个局部变量 x
            for (int x = 0; x < 5; x++)
                Console.Write(
"*");
        }

        
#endregion

        
#region 多个线程引用了一些公用的目标实例的时候,他们共享数据

        
static void SimpleShareMuliThead()
        {
            
//两个线程都调用OutPut方法,他们共享done字段。输出结果是一个Done
            Program prgoram = new Program();
            prgoram.OutPut();
            Thread threadAnother 
= new Thread(new ThreadStart(prgoram.OutPut));
            threadAnother.Start();
        }

        
bool done;

        
public void OutPut()
        {
            
if (!done) { done = true; Console.Write("Done"); }
        }

        
#endregion

        
#region 静态字段提供了另一种线程之间的共享数据

        
static bool outDone; //静态字段,为所有线程共享
        static object locker = new object();

        
static void SimpleShareStaticMulThead()
        {
            Thread threadAnother 
= new Thread(OutDoneFunction);//线程初始化的另一种方法
            threadAnother.Start();
            OutDoneFunction();
        }

        
static void OutDoneFunction()
        {
            
//if (!outDone) { Console.Write("Done"); outDone = true; } //这种情况打印出两个“Done”
            lock (locker)
            {
                
if (!outDone) { Console.Write("Done"); outDone = true; } 
            }
//为了避免这种情况,用lock,锁机制,确定同一时刻只有一个线程进入临界区
            
//  if (!outDone) {  outDone = true; Console.Write("Done");  } //这种情况打印出一个“Done”
        }

        
#endregion