lock

来源:互联网 发布:stl源码 编辑:程序博客网 时间:2024/05/16 18:39

多线程访问同一个资源的时候需要用到锁,当一个线程锁定这个资源,其他线程需要等待它释放才能访问。

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.Threading;namespace @lock{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void showchar(char ch)        {            lock(this)            {                richshow.BeginInvoke((Action)(() => richshow.AppendText(ch.ToString())));            }        }        private void show_a()        {            while(true)            {                showchar('a');                Thread.Sleep(60);            }        }        private void show_A()        {            while (true)            {                showchar('A');                Thread.Sleep(30);            }        }        Thread thread_a = null;        Thread thread_A = null;        private void btnstart_Click(object sender, EventArgs e)        {            thread_a = new Thread(new ThreadStart(show_a));            thread_A = new Thread(new ThreadStart(show_A));            thread_a.Start();            thread_A.Start();            btnstart.Enabled = false;            btnstop.Enabled = true;            text_aacount.Text = "";            text_ACount.Text = string.Empty;        }        private void btnstop_Click(object sender, EventArgs e)        {            thread_a.Abort();            thread_A.Abort();            btnstart.Enabled = true;            btnstop.Enabled = false;        }        private void Count_Click(object sender, EventArgs e)        {            int count_a = 0;            int count_A = 0;            foreach(char c in richshow.Text)            {                if (c == 'a') count_a++;                if (c == 'A') count_A++;            }            text_aacount.Text = count_a.ToString();            text_ACount.Text = count_A.ToString();        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            if (thread_a != null) thread_a.Abort();            if (thread_A != null) thread_A.Abort();        }    }}
0 0
原创粉丝点击