线程暂停与继续
2013-10-11 16:08
260 查看
这篇文章主要是答复百度网友的问题的,代码做了注释,就不解释了。线程的暂停,我使用了WaitOne方法,线程的继续,则使用了set方法,其实,这两种方法都存在于AutoResetEvent类中,这个类主要是通过设置信号量来实现线程的暂停与继续的。
代码如下:
[code]usingSystem.Windows.Forms;
[/code]
实现的效果如下:
当点击“打开10个线程并阻塞”按钮的时候:
当点击“继续运行10个线程”按钮的时候:
代码很简单,源码我就不加上了。
代码如下:
usingSystem;
[code]usingSystem.Windows.Forms;
usingSystem.Threading;
namespaceThreadInUI
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
for(inti=0;i<11;i++)
{
a[i]=newAutoResetEvent(false);//初始化
b[i]=newAutoResetEvent(false);
}
}
string[]threadID=newstring[11];
AutoResetEvent[]a=newAutoResetEvent[11];
AutoResetEvent[]b=newAutoResetEvent[11];
privatevoidbtnStart_Click(objectsender,EventArgse)
{
lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n当前主线程ID为:"+Thread.CurrentThread.ManagedThreadId.ToString();}));
for(inti=0;i<10;i++)
{
intj=i;//这个用于避免闭包
Threadt=newThread(newThreadStart(()=>
{
a[j].WaitOne();//这个用于获取子线程的ID
lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n线程"+threadID[j]+"睡眠3s";}));
Thread.Sleep(3000);
lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n线程"+threadID[j]+"暂停";}));
b[j].WaitOne();//这个用于暂停所有子线程的运作
lblLog.Invoke((Action)(()=>{lblLog.Text+="\r\n===线程"+threadID[j]+"恢复===";}));
}));
threadID[i]=t.ManagedThreadId.ToString();
a[j].Set();//当子线程的ID生成后,这里放行,目的是避免取不到Thread的ID
t.Start();
}
}
privatevoidbtnGoOn_Click(objectsender,EventArgse)
{
for(inti=0;i<10;i++)
{
b[i].Set();//放行所有的子线程
}
}
}
}
[/code]
实现的效果如下:
当点击“打开10个线程并阻塞”按钮的时候:
当点击“继续运行10个线程”按钮的时候:
代码很简单,源码我就不加上了。
相关文章推荐
- 线程暂停与继续实现
- c#如何实现一个线程暂停,等待用户输入文本后继续运行?
- 详解java线程的开始、暂停、继续
- 根据Linux 线程挂起与唤醒原理,实现Sleep的暂停与继续
- QT 线程暂停,继续执行的一种实现(有些道理,而且封装了)
- c#如何实现一个线程暂停,等待用户输入文本后继续运行?
- [POSIX线程模型]_[使用pthread对工作线程进行简单控制-暂停-继续-停止]
- Java 线程暂停与继续
- java实现线程的暂停与继续(详解案例)
- Java线程的暂停与继续
- 线程状态切换 退出-暂停-继续
- Java 线程暂停与继续
- Java 线程暂停与继续
- 猎豹MFC--进程和线程--创建线程AfxBeginThread() SetDlgItemInt()线程暂停继续终止
- MFC 线程的暂停与继续,请问如何做啊。新手
- MFC下暂停、继续、结束AfxBeginThread开启的线程
- MFC下暂停、继续、结束AfxBeginThread开启的线程
- [并发并行]_[pthread]_[对工作线程进行简单控制-暂停-继续-停止]
- [并发并行]_[pthread]_[对工作线程进行简单控制-暂停-继续-停止]
- C# 如何实现一个线程暂停和继续 - 转