双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

一个线程访问冲突的例子,为什么不 崩溃?

wugamp wugamp 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
两个线程同时写一个变量,应该会 崩溃。但是下面的实验没有崩溃。请问怎么回事?
使用方法:启动程序后,textBox1里显示0,按BUTTON1,显示1,再按BUTTON2,则交替显示1和2,不崩溃。

public partial class Form1 : Form
{
Thread t1;
Thread t2;
private int g_var;
private bool bBtn1;
private bool bBtn2;

public Form1()
{
InitializeComponent();
}

public void thread1(object ob)
{
while(true)
{
if (bBtn1)
while (true)
g_var = 1;
Thread.Sleep(10);
}
}

public void thread2(object ob)
{
while (true)
{
if (bBtn2)
while (true)
g_var = 2;
Thread.Sleep(10);
}
}

private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
g_var = 0;
bBtn1 = false;
bBtn2 = false;
t1 = new Thread(thread1);
t1.Start(1);
t2 = new Thread(thread2);
t2.Start();
}

private void button1_Click(object sender, EventArgs e)
{
bBtn1 = true;
}

private void button2_Click(object sender, EventArgs e)
{
bBtn2 = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = g_var.ToString();
}
}
...全文
评论 17
收藏 已收藏
分享
返回顶部
wugamp
C# 111,129 成员 642,540 内容