分享

Thread的Join用法总结【源】

 lhzstudio 2012-05-12
using System;
using System.Threading;

class IsThreadPool
{
    
static Thread regularThread;
    
static void Main()
     {
         regularThread
= new Thread(new ThreadStart(ThreadMethod));
         regularThread.Start();

         ThreadPool.QueueUserWorkItem(
new WaitCallback(WorkMethod));

         Console.ReadLine();
     }

    
static void ThreadMethod()
     {
         Thread.Sleep(
8000);
         Console.WriteLine(
"ThreadOne");
     }

    
static void WorkMethod(object stateInfo)
     {
        
//阻止调用线程(注意:这里是线程池里的后台线程,而不是regularThread),直到regularThread结束才继续进行。
        
//regularThread.Join();

       
//阻止调用线程(这里是线程池里的后台线程)2秒,直到regularThread结束或指定时间已过。
        
//如果该线程在指定的时间内完成了,Join将返回True,否则它返回False。

        if(regularThread.Join(3000))
              Console.WriteLine(
"true");
        
else
              Console.WriteLine(
"false");

         Console.WriteLine(
"ThreadTwo");
     }
}

输出结果:
3秒后输出
false
ThreadTwo
再过5秒(即总共8秒后)输出
ThreadOne

如果将
ThreadMethod() 的Thread.Sleep(8000);注释掉
立即输出结果:

ThreadOne
true
ThreadTwo

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多