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