簡單多線程 非安全實例 與 解決方法

多線程 非安全實例

 

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; }
    }
}

 

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章