【发布时间】:2014-07-17 20:59:23
【问题描述】:
我有三个线程:
- 主要
- thread1
- 线程2
步骤:
- main 线程启动 thread1
- main 线程启动 thread2
- thread1 应该加入 thread2
如何在不使用加入/暂停和恢复的情况下执行此操作。
PS:thread1 不应该知道 thread2 的存在。
我使用suspend和resume来做这个,效果很好,但是我的老板不接受这个解决方案。
一段代码只是为了有个想法。这不是真正的代码。
public class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(() => Thread1Work());
Thread thread2 = new Thread(() => Thread2Work());
Thread thread3 = new Thread(() => StartWork(thread1, thread2));
thread3.Start();
if(CloseProgram())
{
thread2.Abort();
}
}
public static bool CloseProgram()
{
Stopwatch sw = new Stopwatch();
while (true)
{
sw.Start();
while (!EndProgram() && sw.ElapsedMilliseconds < 60000){ }
if (sw.ElapsedMilliseconds > 60000)
{
sw.Stop();
return false;
}
else
{
sw.Stop();
return true;
}
}
}
public static void StartWork(Thread thread1, Thread thread2)
{
thread2.Start();
thread1.Start();
thread2.Suspend();
while (thread2.IsAlive) { }
thread1.Join();
thread2.Resume();
while (!thread2.IsAlive) { }
thread2.Join();
}
public static void Thread2Work()
{
while(true){ DoSomething(); }
}
public static bool EndProgram()
{
if(someThing())
{
return true;
}
else
{
return false;
}
}
public static void Thread1Work()
{
DoOtherThing();
}
}
【问题讨论】:
-
如果第一个工作人员根本不知道,为什么还要等待第二个工作人员?显然,它在概念层面以某种方式依赖于它。此外,如果您这样做,则意味着这些线程正在执行另一个线程可观察到的副作用。这通常是个坏主意。尽量避免这样做。
-
代码在上面,对不起,我昨天没时间发。
标签: c# multithreading join