C# lock关键字:当前代码块只能被一个线程调用,直到用完后才可以被其他线程调用:模拟连续转账:即高并发
lock 关键字
lock关键字可以用来确保代码块完成运行,而不会被其他线程中断,它是通过在代码块运行期间为给定对象获取互斥锁来实现的
lock语句以关键字lock开头,他有一个作为参数的对象,在该参数后面还有一个一次只能有一个线程执行的代码块
Object thisLock =new Object():
lock(thisLock){
//这里面的代码在执行后,才可以进行其他操作,在运行中不可以被中断
}
示例:转账:
可见有多个线程创建并执行,但是运行结果是一个一个执行完
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var target = new Account();
for (int i = 0; i <3; i++)
{
Thread th = new Thread(target.ToFa);
th.Start();
}
Console.Read();
}
}
class Account
{
private int i = 0;
public void ToFa()
{
lock (this)
{
Console.WriteLine("账户余额:" + i);
//暂停2秒,模拟逻辑花费时间
Thread.Sleep(2000);
i += 1000;
Console.WriteLine("转账后的账户余额:" + i.ToString());
}
}
}
}
结果:
最后再来对比去掉lock关键字的情形:
这样的运行在复杂逻辑中有可能是致命的
呵呵哒