C# 了解线程

using System.Threading;

namespace 测试
{
    class 多线程
    {
        //public delegate void ThreadStart();//两个线程代理的原形
        //public delegate void ParameterizedThreadStart(Object obj);
        public static void Main()
        {
            ThreadStart st = new ThreadStart(print);//创建一个线程委托 不带参数
            ParameterizedThreadStart pts = new ParameterizedThreadStart(print); //创建一个线程委托 带参数

            Thread th = new Thread(st);//创建一个线程 th
            Thread th1 = new Thread(pts);//创建一个线程 th1


            th.Start();//启动th线程
            th.Join(); //等待th线程执行完

 

            Data da = new Data(20, "Jin");//实例化一个参数Data由下面定义的
            th1.Start(da);//启动th1线程并且传入参数

            Console.WriteLine("其他事情!");

            Console.Read();
        }

 

        //lock的参数 最佳做法是定义 private 对象来锁定, 或 private static 对象变量来保护所有实例所共有的数据。
        //上面一段话引自MSDN
        private static Object thisLock = new Object();
        public static void print()
        {
            lock (thisLock)//互斥锁
            {
                for (int i = 0; i <= 100; i++)
                {
                    Console.WriteLine(i);
                }
            }
        }
        public static void print(Object o)
        {
            Data da = (Data)o;
            Console.WriteLine(da.name);
            for (int i = 0; i <= da.max; i++)
                Console.WriteLine(i);
        }
    }
    //作为参数传递的类
    public struct Data
    {
        public int max;
        public string name;
        public Data(int _max, string _name)
        {
            max = _max;
            name = _name;
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值