using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Test
{
class Demo2
{
//线程之间可以通过static变量来共享数据。
private static bool _isExecute = false;
static void Main()
{
new Thread(Execute).Start();//启动线程,执行方法Execute一次
new Thread(Execute).Start();//启动线程,再执行方法Execute一次
Console.ReadLine();
}
static void Execute()
{
if (!_isExecute)
{
Console.WriteLine("Execute");
_isExecute = true;//当变量变成true会执行一次或者两次
}
}
}
}
输出截图:
有时候是下面这样的:
有时候是这样的:
上面这种情况不会一直发生,因为第一个线程还没有来得及
把_isDone设置成true,第二个线程就进来了,而这不是我们
想要的结果,在多个线程下,结果不符合我们的需求,这就是线程不安全
下面是加上锁后的代码:
private static bool _isExecute = false;
private static object _lock = new object();创建锁
static void Main()
{
new Thread(Execute).Start();
new Thread(Execute).Start();
Console.ReadLine();
}
static void Execute()
{
lock (_lock)上锁
{
if (!_isExecute)
{
Console.WriteLine("Execute"); //
_isExecute = true;
}
}
}
在我们加上锁之后,被锁住的代码在同一个时间内只允许一个
线程访问,其它的线程会被阻塞,只有等到这个锁被释放之后
其它的线程才能执行被锁住的代码。
输出截图: