写一个点击开启循环线程,线程被阻塞,再次点击解除阻塞
时间: 2024-02-06 08:14:46 浏览: 16
好的,这是一个C#的问题,以下是一个示例代码实现:
```csharp
using System.Threading;
public class ThreadExample
{
private bool _isRunning = false;
private Thread _thread;
public void StartThread()
{
if (_isRunning)
{
// 线程已经在运行,不需要再次开启
return;
}
_isRunning = true;
_thread = new Thread(DoWork);
_thread.Start();
}
public void StopThread()
{
if (!_isRunning)
{
// 线程已经停止,不需要再次停止
return;
}
// 设置 _isRunning 为 false,使线程停止
_isRunning = false;
// 等待线程结束
_thread.Join();
}
private void DoWork()
{
while (_isRunning)
{
// 线程被阻塞在这里
Thread.Sleep(500);
}
}
}
```
在上面的示例代码中,我们定义了一个 `ThreadExample` 类,其中包含 `StartThread` 和 `StopThread` 两个方法,用于开启和停止循环线程。当调用 `StartThread` 方法时,会创建一个新的线程并执行 `DoWork` 方法,该方法包含一个循环,每次循环会阻塞线程 500 毫秒,直到 `_isRunning` 被设置为 false。当调用 `StopThread` 方法时,会将 `_isRunning` 设置为 false 来停止线程,并等待线程结束。
你可以将以上代码复制到你的代码编辑器中,进行编译和测试。