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
- LOCK
- LOCK
- lock
- lock
- Lock
- Lock()
- lock
- LOCK
- Lock
- Lock
- Lock
- lock
- lock
- Lock
- Lock
- Lock
- Lock
- lock
- 封闭开发终于结束了,回归我的博客,回归各个社区,回归“业余生活”....
- 第九周项目1--复数类中的运算符重载(续)
- <Unity3D>Unity3D GUI控件
- hdu5094 状态压缩+bfs
- 2015年大一下第7周项目4-我的向量类
- lock
- Gson解析复杂的json数据
- 背景建模技术(二):BgsLibrary的框架、背景建模的37种算法性能分析、背景建模技术的挑战
- 微博随便看看
- oc内存管理
- 第9周项目1——复数类中的运算符重载(续)
- 2015年第九周项目二:Time类中的运算符重载(续)(1)
- 第十周上机项目3分数类中的运算符重载
- 第九周(运算符重载分数类)