线程同步

zhouats2000 2006-04-17 11:25:16

     th1 = New Thread(New ThreadStart(AddressOf Me.Run_HS))
th2 = New Thread(New ThreadStart(AddressOf Me.Run_BS))
th1.Name = "HS"
th2.Name = "BS"

th1.IsBackground = True
th2.IsBackground = True

th1.Start()
th2.Start()

th1.Join()
th2.Join()


线程th1和th2运行没问题,但是th1先执行完,我想让th1等待th2执行完后,一起退出,并显示结果,不知使线程同步。

请各位支招,谢谢。
...全文
187 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhouats2000 2006-04-19
  • 打赏
  • 举报
回复
>>> 我想让th1等待th2执行完后,一起退出,并显示结果
啥意思?一起退出?

====================================
一起退出, Th1,Th2两线程同时结束
SeeSunSet 2006-04-19
  • 打赏
  • 举报
回复
private ReaderWriterLock rwl = new ReaderWriterLock();
private Thread thdProduce = null;
private Thread thdConsume = null;
private int m_iCounter = 0;
// 生产者线程函数
private void ThreadProduce()
{
while(true)
{
rwl.AcquireWriterLock(Timeout.Infinite);
while(m_iCounter < 1000)
{
m_iCounter++;
labProduce.Text = m_iCounter.ToString();
Thread.Sleep(10);
}
rwl.ReleaseWriterLock();
}
}
// 消费者线程函数
private void ThreadConsume()
{
while(true)
{
rwl.AcquireReaderLock(Timeout.Infinite);//无限长时间等待Infinite
while(m_iCounter > 0)
{
m_iCounter--;
labConsume.Text = m_iCounter.ToString();
Thread.Sleep(10);
}
rwl.ReleaseReaderLock();
}
}
// 启动线程的运行。
private void button1_Click(object sender, System.EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
thdProduce = new Thread(new ThreadStart(this.ThreadProduce));
thdConsume = new Thread(new ThreadStart(this.ThreadConsume));
if(thdProduce != null)
thdProduce.Start();
if(thdConsume != null)
thdConsume.Start();
}
// 停止线程的运行。
private void button2_Click(object sender, System.EventArgs e)
{
rwl.ReleaseLock();
if(thdProduce != null)
thdProduce.Abort();
thdProduce = null;
if(thdConsume != null)
thdConsume.Abort();
thdConsume = null;
button1.Enabled = true;
button2.Enabled = false;
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
rwl.ReleaseLock();
if(thdProduce != null)
thdProduce.Abort();
if(thdConsume != null)
thdConsume.Abort();
}
}
tslxm2003 2006-04-19
  • 打赏
  • 举报
回复
可以设置一个标志变量来判断TH2的执行情况,根据标志来判断TH2是否已经执行完成,然后退出两个线程.
shalen520 2006-04-19
  • 打赏
  • 举报
回复
一起退出, Th1,Th2两线程同时结束
==============================
没可能,一定有先后顺序
真相重于对错 2006-04-18
  • 打赏
  • 举报
回复
ms-help://MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfsystemthreadingmutexclasstopic.htm
速马 2006-04-17
  • 打赏
  • 举报
回复
>>> 我想让th1等待th2执行完后,一起退出,并显示结果
啥意思?一起退出?
荣之梦 2006-04-17
  • 打赏
  • 举报
回复
纯支持

16,555

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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