C#多线程学习笔记

1、首先引入Thread类库

using System.Threading;

2、创建线程,分为有参和无参

static void show1(){
    Console.WriteLine("无参的线程");
}
static void show2(Object s){//这里的参数必须是Object类型
    Console.WriteLine("有参的线程,参数:"+s.toString());
}
static void Main(){
    Thread t1 = new Thread(show1);//无参第一种方法,直接传入函数名
    Thread t2 = new Thread(new ThreadStart(show1));//无参第二种,利用ThreadStart对象
    Thread t3 = new Thread(delegate(){Console.WriteLine("无参的线程");});//无参第三种,匿名函数
    Thread t4 = new Thread(()=>{Console.WriteLine("无参的线程");});无参第四种,lambda表达式

    t1.IsBackground = true;//是否后台,是则当主线程结束时,子线程同时结束
    t1.Start();//开启线程
    t2.Start();
    t3.Start();
    t4.Start();

    Thread t5 = new Thread(new ParameterizedThreadStart(show2));//利用ParameterizedThreadStart对象
    t5.Start("Hello");//通过Start传递参数
}

3、线程锁lock

当多个线程操纵同一资源(如共用一个静态变量),需要加线程锁

如下,不加线程锁时

    //通过t1 t2两个线程,访问数组arr,i代表访问下标,每访问一次自增一次
    class Program
    {
        static int[] arr = { 1,2,3,4,5,6,7,8,9};
        static int i = 0;
        static void Main(string[] args)
        {
            Program p = new Program();
            Thread t1 = new Thread(p.th);
            Thread t2 = new Thread(p.th);
            t1.IsBackground = true;
            t2.IsBackground = true;
            t1.Start();
            t2.Start();
            Console.ReadLine();
        }  
        public void th()
        {
            if (i <= 8) 
            {
                Console.WriteLine(arr[i]);
                i += 1;
                th();
            }
        }     
    } 

结果并不是从1-9

1
1
3
4
5
6
7
8
9
2

以为时间片分配等原因,每次结果可能都不一样,所以必须加上锁

    public void th()
        {
            lock ("abc")//线程锁lock,abc是类似标识符的作用
            {
                if (i <= 8) 
                {
                    Console.WriteLine(arr[i]);
                    i += 1;
                    th();
                }
            }
        }

再执行发现正常

猜你喜欢

转载自www.cnblogs.com/gaokaitai/p/10644076.html