Lock线程同步

本文探讨了C#中的lock关键字在并发编程中的应用,通过实例展示了如何使用lock锁定string变量以防止竞态条件。重点讲解了锁的作用域、值类型与引用类型的区别,以及在防止数据不确定性和确保安全性方面的重要作用。
摘要由CSDN通过智能技术生成

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

namespace ConsoleApp1
{
class Pragram
{
/*
可以看出,str01和str02是两个string类型的变量,但是当lock(str01)之后,str02变成了临界区被多订导致th2中lock(){}
体处于等待状态。这就对应了只要在应用进程中任何位置处具有相同内容的字符串放置了,就将锁定应用程序中与该字符串具有相同内容的字符串
lock锁定的对象是一个程序块的内存边界
值类型不能被Lockm因为前文标红字的对象被释放 值类型不是引用类型
应用场景 经常会应用于防止多线程操作导致公用变量值出现不确定的一场,用于确保操作的安全性
*/
//static string str01 = “name”;
//static string str02 = “name”;
static People stu = new People();
static void Main(string[] args)
{
ThreadClass tc = new ThreadClass(stu);
Thread th1 = new Thread(new ThreadStart(tc.Thread01));
th1.Start();

        ThreadClass tc2 = new ThreadClass(stu);
        Thread th2 = new Thread(new ThreadStart(tc2.Thread01));
        th2.Start();
        Console.Read();
    }

    
    static void printQueue(Queue q) 
    {
        //declare and initialize a Queue
        Queue que = new Queue();
        //insertting elements
        que.Enqueue(100);
        que.Enqueue(200);
        que.Enqueue(300);
        que.Enqueue(400);

        //printing queue elements
        Console.WriteLine("Queue elements are...");
        printQueue(que);
        //hit Enter to exit
        Console.ReadLine();
        foreach (Object obj in q)
        {
            Console.WriteLine(obj + " ");
        }
        Console.WriteLine();
    }
}
class People
{

}
class ThreadClass
{
    People stu;
    string str;
    string path;
    public ThreadClass(People stu)
    {
        this.str = str;
        this.path = path;
        this.stu = stu;
    }
    public void Thread01()
    {
        lock (stu)//lockstu之后,stu成为临界区被锁定,其他线程等待该lock(){}执行完stu并释放
        {
            for (int i = 0; i < 10; i++) Console.WriteLine(i);
        }
    }
}

class threda
{
    public static sss obj = new sss();

    public void hhh()
    {
        lock (obj)
        {
            for (int i = 0; i < 7; i++)
            {
                Thread.Sleep(500);

                if (obj.i > 0)
                {
                    obj.i--;
                    Console.WriteLine("当前线程名" + Thread.CurrentThread.Name + ", obj.i=" + obj.i);
                }
            }
        }
    }
}
/*
 加锁和不加锁运行的结果有区别
加锁后:i的值会一个个递减,不会出现跳跃,不会出现重复,一直到0值
不加锁:i的值输出会出现跳跃
枷锁后,一个时刻只能有一个线程执行被锁区域的代码,两个线程都是有先后顺序执行的,所以不会出现间断输出
 */
class sss
{
    public int i;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值