尋尋覓覓

共同奉獻

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

多线程 非安全实例

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadSample
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
int numThreads = 20;
            ShareState state 
= new ShareState();
            Thread[] threads 
= new Thread[numThreads];
            
for (int i = 0; i < numThreads; i++)
            {
                threads[i] 
= new Thread(new Task(state).DoTheTask);
                threads[i].Start();
            }
            
for (int i = 0; i < numThreads; i++)
            {
              threads[i].Join();  
            }
            Console.WriteLine(
"ShareState.State最后结果是:" + state.State);
            Console.ReadLine();
        }
    }
    
public class Task
    {
        ShareState shareState;
        
public Task(ShareState shareState)
        {
            
this.shareState = shareState;
        }
        
public void DoTheTask()
        {
            
///设为5000,数据大点更能 看到线程非安全的效果
            for (int i = 0; i < 5000; i++)
            {
                shareState.State 
+= 1;
            }
        }
    }
    
public class ShareState
    {
        
public int State { getset; }
    }

}

 

解决方法的实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadSample02
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
int numThreads = 20;
            ShareState state 
= new ShareState();
            Thread[] threads 
= new Thread[numThreads];
            
for (int i = 0; i < numThreads; i++)
            {
                threads[i] 
= new Thread(new Task(state).DoTheTask);
                threads[i].Start();
            }
            
for (int i = 0; i < numThreads; i++)
            {
                threads[i].Join();
            }
            Console.WriteLine(
"ShareState.State最后结果是:" + state.State);
            Console.ReadLine();
        }
    }
    
public class Task
    {
        ShareState shareState;
        
public Task(ShareState shareState)
        {
            
this.shareState = shareState;
        }
        
public void DoTheTask()
        {
            
///设为5000,数据大点更能 看到线程非安全的效果
            for (int i = 0; i < 5000; i++)
            {
                
lock (shareState)
                {
                    shareState.State 
+= 1;
                }
            }
        }
    }
    
public class ShareState
    {
        
public int State { getset; }
    }
}

 

 

posted on 2011-08-14 13:03  ★海戰鷹  阅读(248)  评论(0编辑  收藏  举报