求最佳线程同步方法 100分

不慕繁华 2012-10-26 07:14:04
private Thread monitor;
private Thread temp;
List<int> intListA;
List<int> intListB;
private int i = 0;
private int j = 0;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
intListA = new List<int>(10);
intListB = new List<int>(10);
timer1.Interval = 200;
timer2.Interval = 200;
this.timer1.Enabled = true;
this.timer2.Enabled = true;
}

private void timer1_Tick(object sender, EventArgs e)
{
monitor = new Thread(new ThreadStart(AA));
monitor.Start();
}
private void AA()
{

DateTime dt = DateTime.Now;
i++;
intListA.Add(i);
string str = "A的个数:" + intListA.Count + "值:" + i + " 【" + dt.Second + "分" + dt.Millisecond.ToString() + "】";
Add(str);
temp = new Thread(new ThreadStart(match));
temp.Start();
}

private void timer2_Tick(object sender, EventArgs e)
{
temp = new Thread(new ThreadStart(BB));
temp.Start();
}
private delegate void AddItem(string item);
private void Add(string item)
{
if (this.listBox1.InvokeRequired)
{
AddItem add = new AddItem(Add);
this.listBox1.Invoke(add, new object[] { item });
}
else
{
this.listBox1.Items.Add(item);
}
}
private void BB()
{
DateTime dt = DateTime.Now;
j++;
intListB.Add(j);
Thread.Sleep(50);
string str = "B的个数:" + intListB.Count + "值:" + j + " 【" + dt.Second + "分" + dt.Millisecond.ToString() + "】";
Add(str);
temp = new Thread(new ThreadStart(match));
temp.Start();
}
private void match()
{
if (intListA.Count > 0)
{
if (intListA[0] == intListB[0])
{
Thread.Sleep(20);
DateTime dt = DateTime.Now;
string str = "匹配" + " 【" + dt.Second + "分" + dt.Millisecond.ToString() + "】";
Add(str);
intListA.RemoveAt(0);
intListB.RemoveAt(0);
Thread.Sleep(1000);
}
}
}
...全文
236 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
冰镇宝贝321 2012-10-31
  • 打赏
  • 举报
回复

set
{
lock (syncLock)
{
_threadInUsing = value;
}
}
get
{
lock (syncLock)
{
return _threadInUsing;
}
}




locklocklocklocklocklocklocklocklocklocklocklocklock

XBodhi. 2012-10-31
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 的回复:]

lock
ReaderWriterLockSlim
Monitor
[/Quote]


这个不错。哈。
SocketUpEx 2012-10-31
  • 打赏
  • 举报
回复
lock
ReaderWriterLockSlim
Monitor

聖傑 2012-10-31
  • 打赏
  • 举报
回复
lock语句
modyaj 2012-10-30
  • 打赏
  • 举报
回复
进入共享区(变量)的时候加 出来就释放
mngzilin 2012-10-27
  • 打赏
  • 举报
回复
lock(obj)
{
list.add() or remove()
}
不慕繁华 2012-10-26
  • 打赏
  • 举报
回复
具体这个程序改怎么对线程加锁,如梦能给详细讲讲吗?看不太懂啊

110,526

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧