线1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;

namespace WaitAndPulse
{
    public class ClassFor
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 15; i++)
            {
                Thread thread = new Thread(new ThreadStart(myThread1));
                thread.Start();

  
//thread.Join(); } Console.WriteLine("主线程"); Console.ReadKey(); } static object ob = new object(); static int count1 = 0; public static void myThread1() { Monitor.Enter(ob);  //作用域开始 Thread.Sleep(10); Console.WriteLine("1测试线程{0}", ++count1); Monitor.Exit(ob);  //作用域结束 } } }

注意有无标注地方的区别。

IsBackground对线程的重要作用

要点:

1、当在主线程中创建了一个线程,那么该线程的IsBackground默认是设置为FALSE的。

2、当主线程退出的时候,IsBackground=FALSE的线程还会继续执行下去,直到线程执行结束。

3、只有IsBackground=TRUE的线程才会随着主线程的退出而退出。

4、当初始化一个线程,把Thread.IsBackground=true的时候,指示该线程为后台线程。后台线程将会随着主线程的退出而退出。

5、原理:只要所有前台线程都终止后,CLR就会对每一个活在的后台线程调用Abort()来彻底终止应用程序。

 

PS:后台线程必须受制于前台线程,当主线程结束所有后台线程必须结束,例如我们聊天软件,我们关闭聊天软件那么软件就木有检查谁谁上线下线了。通常,后台线程非常适合于完成后台任务,应该将被动侦听活动的线程设置为后台线程,而将负责发送数据的线程设置为前台线程,这样,在所有的数据发送完毕之前该线程不会被终止

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Threading;

namespace WaitAndPulse
{
    public class ClassFor
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("测试我的线程开始");

                Thread test1 = new Thread(new ThreadStart(myThread1));
                test1.Priority = ThreadPriority.Lowest;
                test1.Start();

                Thread test2 = new Thread(new ThreadStart(myThread2));
                test1.Priority = ThreadPriority.Highest;
                test2.Start();

                Thread test3 = new Thread(new ThreadStart(myThread3));
                test1.Priority = ThreadPriority.Normal;
                test3.Start();

                Console.WriteLine("结束");
                Console.ReadKey();
            }

            public static void myThread1()
            {
                Console.WriteLine("我的线程1");
            }
            public static void myThread2()
            {
                Console.WriteLine("我的线程2");
            }
            public static void myThread3()
            {
                Console.WriteLine("我的线程3");
            }
        }
    }
}

 

嘿嘿,看到木有,在我的代码中,1,2,3本来是依次调用,但是执行的时候出现了变化,原因是我设置了线程的优先级

Priority是Thread类的属性,主要是影响线程的优先级,提示一个枚举类型的值,优先级排列如下:Highest > AboveNormal >  Normal >  BelowNormal > Lowest,不过建议不要随便设置优先级,不然容易造成死锁哦。

 

原文地址:https://www.cnblogs.com/jiaoluo/p/3548704.html