首页 > 编程语言 >通过实例学C#之Thread类

通过实例学C#之Thread类

时间:2024-04-11 12:58:24浏览次数:23  
标签:IsAlive Thread C# t1 Start 实例 线程 Console

构造函数

Thread(ThreadStart)

该构造函数接受一个不带参数的方法。

static void Main(string[] args)
{
    Thread t1 = new Thread(new ThreadStart(ThreadMethod1));
    t1.Start();

    Console.ReadKey();
}

static void ThreadMethod1()
{
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine($"分线程t1:{i}");
        Thread.Sleep(1000);
    }
}

运行结果:

分线程t1:0
分线程t1:1
分线程t1:2
分线程t1:3
分线程t1:4

Thread(ParameterizedThreadStart)

该方法接收一个带参数的方法,且方法的参数类型必须为object。

static void Main(string[] args)
{
    Thread t2=new Thread(new ParameterizedThreadStart(ThreadMethod2));
    t2.Start(5);

    Console.ReadKey();
}

static void ThreadMethod2(object obj)
{
    for(int i = 0;i < (int)obj; i++)
    {
        Console.WriteLine($"分线程t2:{i}");
        Thread.Sleep(1000);
    }
}

运行结果:

分线程t2:0
分线程t2:1
分线程t2:2
分线程t2:3
分线程t2:4

常用属性

IsAlive

获取指示当前线程的执行状态的值。

static void Main(string[] args)
{
    Thread t1 = new Thread(new ThreadStart(ThreadMethod1));
    Console.WriteLine($"调用Start方法前IsAlive:{t1.IsAlive}");

    t1.Start();
    Console.WriteLine($"调用Start方法后IsAlive:{t1.IsAlive}");

    Thread.Sleep(6000);
    Console.WriteLine($"分线程方法执行完后IsAlive:{t1.IsAlive}");

    Console.ReadKey();
}

static void ThreadMethod1()
{
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine($"分线程t1:{i}");
        Thread.Sleep(1000);
    }
}

运行结果:

调用Start方法前IsAlive:False
调用Start方法后IsAlive:True
分线程t1:0
分线程t1:1
分线程t1:2
分线程t1:3
分线程t1:4
分线程方法执行完后IsAlive:False

可见,即使当线程创建以后,只要没有调用Start(),线程的IsAlive仍为false,而当线程方法执行结束以后,该值也为false。所以,可以用该值判断分线程方法执行结束与否。


IsBackground

当分线程不是背景线程时,程序执行完主线程以后,如果分线程没执行完,继续执行分线程;而一旦分线程是背景线程,那么当主线程执行结束后,如果分线程没执行完,也会跟着主线程一起结束。


ThreadState

获取一个值,该值包含当前线程的状态。

static void Main(string[] args)
{
    Thread t1= new Thread(new ThreadStart(ThreadMethod1));
    Console.WriteLine($"t1实例化未执行Start()方法前threadState为:{t1.ThreadState}");
    t1.Start();
    Console.WriteLine($"t1执行Start()方法后threadState为:{t1.ThreadState}");
    Thread.Sleep(6000);
    Console.WriteLine($"线程方法结束后threadState为:{t1.ThreadState}");

    Console.ReadKey();
}

static void ThreadMethod1()
{
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine($"分线程t1:{i}");
        Thread.Sleep(1000);
    }
}

运行结果:

t1实例化未执行Start()方法前threadState为:Unstarted
t1执行Start()方法后threadState为:Running
分线程t1:0
分线程t1:1
分线程t1:2
分线程t1:3
分线程t1:4
线程方法结束后threadState为:Stopped

与IsAlive一样,可以通过此参数来确定当前线程状态,且状态比IsAlive多。


常用方法

Start(),Start(Object)

启动线程,将线程的IsAlive属性从false变为true,ThreadState属性从Unstarted变为Running。如果创建分线程中,使用的方法带有object类参数,那么调用Start()方法时,也必须带有对应的object参数。


Abort()

当线程调用Start()以后,在线程还没结束时,调用Abort(),会停止线程,并让线程的IsAlive与ThreadState属性发生变化。

static void Main(string[] args)
{
    Thread t1= new Thread(new ThreadStart(ThreadMethod1));
    t1.Start();

    Console.WriteLine($"t1执行Start()方法后threadState为:{t1.ThreadState}");
    Console.WriteLine($"t1执行Start()方法后IsAlive:{t1.IsAlive}");

    Thread.Sleep(2000);

    t1.Abort();
    Console.WriteLine($"调用Abort()方法后threadState为:{t1.ThreadState}");
    Console.WriteLine($"调用Abort()方法后IsAlive:{t1.IsAlive}");

    Thread.Sleep(2000);
    t1 = new Thread(new ThreadStart(ThreadMethod1));
    t1.Start();
    Console.WriteLine($"t1再次执行Start()方法后threadState为:{t1.ThreadState}");
    Console.WriteLine($"t1再次执行Start()方法后IsAlive:{t1.IsAlive}");

    Console.ReadKey();
}

static void ThreadMethod1()
{
    for (int i = 0; i < 5; i++)
    {
        Console.WriteLine($"分线程t1:{i}");
        Thread.Sleep(1000);
    }
}

运行结果:

分线程t1:0
t1执行Start()方法后threadState为:Running
t1执行Start()方法后IsAlive:True
分线程t1:1
调用Abort()方法后threadState为:Aborted
调用Abort()方法后IsAlive:False
t1再次执行Start()方法后threadState为:Running
t1再次执行Start()方法后IsAlive:True
分线程t1:0
分线程t1:1
分线程t1:2
分线程t1:3
分线程t1:4

当线程调用Abort()以后,如果希望重新启动线程,必须再一次对线程进行实例化后调用Start()函数,而不能直接调用Start()函数,不然会报错。


Join()

执行该方法后,后面的代码,必须在使用Join()的线程执行完以后才能执行。

 static void Main(string[] args)
 {
     Thread t1= new Thread(new ThreadStart(ThreadMethod1));
     
     Thread t2=new Thread(new ParameterizedThreadStart(ThreadMethod2));
     t2.Start(5);
     t2.Join();
     t1.Start();

     Console.ReadKey();
 }

static void ThreadMethod1()
{
    for (int i = 0; i <5; i++)
    {
        Console.WriteLine($"分线程t1:{i}");
        Thread.Sleep(1000);
    }

}

 static void ThreadMethod2(object obj)
 {
     for(int i = 0;i < (int)obj; i++)
     {
         Console.WriteLine($"分线程t2:{i}");
         Thread.Sleep(1000);
     }
 }

运行结果:

分线程t2:0
分线程t2:1
分线程t2:2
分线程t2:3
分线程t2:4
分线程t1:0
分线程t1:1
分线程t1:2
分线程t1:3
分线程t1:4

Sleep(Int32)

将当前线程挂起指定的毫秒数。


标签:IsAlive,Thread,C#,t1,Start,实例,线程,Console
From: https://blog.csdn.net/lgh65200/article/details/137613569

相关文章

  • 52 Things: Number 5: What is meant by the complexity class NP?
    Thisisthelatestinaseriesofblogpoststoaddressthelistof '52ThingsEveryPhDStudentShouldKnow' todoCryptography:asetofquestionscompiledtogivePhDcandidatesasenseofwhattheyshouldknowbytheendoftheirfirstyear.......
  • 52 Things: Number 4: The Complexity Class P
    52Things:Number4:TheComplexityClassP52件事:数字4:复杂度等级PThisisthefourthblogposttalkingabout '52ThingsEveryPhDStudentShouldKnow' todoCryptography,andthefirstonthetopicofTheoreticalComputerScience.Inthispost,......
  • 52 Things: Number 8: How does interaction help in computation, and what is the c
    52Things:Number8:Howdoesinteractionhelpincomputation,andwhatistheclassIP?52件事:数字8:交互如何帮助计算,什么是类IP? Thisisthelatestinaseriesofblogpoststoaddressthelistof'52ThingsEveryPhDStudentShouldKnowToDoCryptogr......
  • 52 Things: Number 7: How does randomness help in computation, and what is the cl
    52Things:Number7:Howdoesrandomnesshelpincomputation,andwhatistheclassBPP?52件事:数字7:随机性如何帮助计算,BPP类是什么?Thisisthelatestinaseriesofblogpoststoaddressthelistof'52ThingsEveryPhDStudentShouldKnowToDoCryptogr......
  • 52 Things: Number 12: What is the elliptic curve group law?
    52Things:Number12:Whatistheellipticcurvegrouplaw?52件事:数字12:什么是椭圆曲线群定律?Thisisthelatestinaseriesofblogpoststoaddressthelistof '52ThingsEveryPhDStudentShouldKnow' todoCryptography:asetofquestionscompiled......
  • 52 Things: Number 11: What are the DLP, CDH and DDH problems?
    52Things:Number11:WhataretheDLP,CDHandDDHproblems?52件事:数字11:DLP、CDH和DDH问题是什么? Thisisthelatestinaseriesofblogpoststoaddressthelistof'52ThingsEveryPhDStudentShouldKnowToDoCryptography':asetofquestion......
  • LeetCode 面试经典150题---005
    ####135.分发糖果n个孩子站成一排。给你一个整数数组ratings表示每个孩子的评分。你需要按照以下要求,给这些孩子分发糖果:每个孩子至少分配到1个糖果。相邻两个孩子评分更高的孩子会获得更多的糖果。请你给每个孩子分发糖果,计算并返回需要准备的最少糖果数目。n==rat......
  • 52 Things: Number 10: What is the difference between the RSA and strong-RSA prob
    52Things:Number10:WhatisthedifferencebetweentheRSAandstrong-RSAproblem?52件事:数字10:RSA和强RSA问题有什么区别?Thisisthelatestinaseriesofblogpoststoaddressthelistof'52ThingsEveryPhDStudentShouldKnowToDoCryptography......
  • The 2022 ICPC Asia Hangzhou Regional Programming Contest
    目录写在前面FDCKAGM写在最后写在前面比赛地址:https://codeforces.com/gym/104090。以下按个人难度向排序。最上强度的一集,然而金牌题过了铜牌题没过,唐!去年杭州似在一道树上痛失Au呃呃,vp2022树题过了然而铜牌题没过呃呃F签到。大力模拟。codebydztle:#include<bit......
  • Understanding the linux kernel Chapter 7 Process Scheduling
    SchedulingPolicyLinuxschedulingisbasedonthetimesharingtechnique:severalprocessesrunin“timemultiplexing”becausetheCPUtimeisdividedintoslices(called,quantum),oneforeachrunnableprocess.Analternativeclassificationdistinguis......