C# 多线程有关问题 怎么防止线程重复运行
C# 多线程问题 如何防止线程重复运行
我的代码如下,我的想法是,我开10个线程,如果一个线程满足了条件了(flag=true),就结束所有线程。
但我的代码一运行,实际上还是执行了10次,实际我的想法是满足条件后执行一次就可以了,其他线程不在执行。请问要如何才能实现。
------解决方案--------------------
我的代码如下,我的想法是,我开10个线程,如果一个线程满足了条件了(flag=true),就结束所有线程。
但我的代码一运行,实际上还是执行了10次,实际我的想法是满足条件后执行一次就可以了,其他线程不在执行。请问要如何才能实现。
public static bool flag=true;
private void button1_Click(object sender, EventArgs e)
{
Thread[] threads = new Thread[10];
Mutex mt = new Mutex();
mt.WaitOne();
for (int i = 0; i < 10; i = i + 1)
{
threads[i] = new Thread(funKK);
threads[i].Name = "线程" + (i).ToString();
threads[i].Start();
}
mt.ReleaseMutex();
}
private void funKK()
{
while(true)
{
if (flag==false) //flag=false时退出当前循环
{
break;
}
if (flag==true) //条件满足时执行。
{
this.Invoke((MethodInvoker)delegate
{
richTextBox1.Text += "运行中...\n";
flag=false;
});
}
}
}
------解决方案--------------------
public static bool flag = true;
private void button1_Click(object sender, EventArgs e)
{
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i = i + 1)
{
threads[i] = new Thread(funKK);
threads[i].Name = "线程" + (i).ToString();
threads[i].Start();
}
}
private void funKK()
{
while (true)
{
Mutex mt = new Mutex(false,"test");