简单多线程 非安全实例 与 解决方法

探讨多线程非安全实例及解决方法
本文深入分析了多线程编程中非安全实例的问题,并通过实例展示了如何解决线程同步问题,确保共享状态的一致性。

多线程 非安全实例

 

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

 

 

转载于:https://www.cnblogs.com/kaka5q/archive/2011/08/14/2137850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值