在睡眠/等待期间退出一个线程

时间:2015-07-18 15:29:57

标签: multithreading

在睡眠/等待时是否可以用任何语言杀死一个线程?

我的情景: 我有两个线程,一个是不断寻找数据流中的上升沿,我们称之为EdgeThread,一个是根据上升沿之间的差异设置变量,让我们称之为DifThread。主程序正在绘制这些数据。

如果EdgeThread在DifThread完成设置变量之前检测到另一个上升沿(每次变量之间休眠.5秒),则DifThread需要立即停止并重新启动,即使它正在休眠。

1 个答案:

答案 0 :(得分:1)

Java等语言或.NET平台中的任何语言都支持某种形式的线程等待/通知机制。

这个想法是,不是简单地让线程sleep持续一段时间,而是在一个对象上有线程wait,同时指定等待时间的超时时间,行为与sleep类似。

这是一个非常人为的例子,受你的需求描述的启发,说明了这个机制如何使用.NET / C#(你可以自己尝试这个小例子):

private static readonly object objLock = new object();
private static volatile bool shouldIRelaunch = false;

static void Main(string[] args)
{
    Thread difThread = new Thread(() =>
    {
        while (!shouldIRelaunch)
        {
            Console.WriteLine("difThread - doing some work...");

            // Now, instead of sleeping, perform a wait which a pulse can interrupt.
            lock (objLock)
            {
                Monitor.Wait(objLock, 500);
            }
        }

        Console.WriteLine("difThread - Exiting thread...");
    });

    Thread edgeThread = new Thread(() =>
    {
        Console.WriteLine("edgeThread - sleeping for a few seconds...");
        Thread.Sleep(5000);
        lock (objLock)
        {
            shouldIRelaunch = true;
            Monitor.Pulse(objLock);
            Console.WriteLine("edgeThread - Notiying difThread thread to interrupt the wait");
        }
    });

    difThread.Start();
    edgeThread.Start();
}

上面的代码片段产生以下输出:

difThread - doing some work...
edgeThread - sleeping for a few seconds...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
difThread - doing some work...
edgeThread - Notiying difThread thread to interrupt the wait
difThread - Exiting thread...

.NET语言的相关文档:Monitor.Wait()Monitor.Pulse()

对于Java:Guarded Blocks

Java也有打断你可能感兴趣的睡眠的概念。有关详细信息,请参阅此处:Interrupts