线程同步(1)

使用Monitor或lock进行线程同步的例子:

using System;
using System.Threading;

namespace Test
{
    
class Program{
    
        
static long counter = 1;
        
        
static void Main()
        
{
            Thread t1 
= new Thread(f1);
            Thread t2 
= new Thread(f1);
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            
if(counter != 1048576)
                Console.Read();
        }


        
static void f1()
        
{
            
for (int i = 0; i < 10; i++)
            
{
                
/// 方法1:
                
/// 在多线程程序中,没有同步,所以
                
/// 会出现混乱状态。

                counter *= 2;

                
/// 方法2:
                
/// 用Monitor同步,可用于多线程。

                //Monitor.Enter(typeof(Program));
                
//try { counter *= 2; }
                
//finally { Monitor.Exit(typeof(Program)); }

                
/// 方法3:
                
/// C#语言用lock替代Monitor的Enter、Exit,使用方法更简洁。

                //lock (typeof(Program)) { counter *= 2; }

                Console.WriteLine(
"counter*2 {0}", counter);
                Thread.Sleep(
10);
            }

        }

    }

}


创建一个BAT脚本,调用这个程序30次。运行这个脚本。

如果用方法1,脚本可能在某个地方停下来。这时一定出现了混乱状态。

如果使用方法2或方法3,脚本不会停下来。多线程同步正确。

using System;
using System.Threading;

namespace Test
{
    
class Program{
    
        
static long counter = 1;
        
static object _syncRoot = new object();

        
static void Main()
        
{
            Thread t1 
= new Thread(f1);
            Thread t2 
= new Thread(f1);
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            
if(counter != 1048576)
                Console.Read();
        }


        
static void f1()
        
{
            
for (int i = 0; i < 10; i++)
            
{
                
/// 方法4:
                lock (_syncRoot) { counter *= 2; }

                Console.WriteLine(
"counter*2 {0}", counter);
                Thread.Sleep(
10);
            }

        }

    }

}



posted @ 2008-06-19 12:03  h2appy  阅读(178)  评论(0编辑  收藏  举报