c# 多线程

 static void PrintNumbers()
        {
            Console.WriteLine("Starting...");
            for (int i = 0; i <= 10; i++)
            {
                Console.WriteLine(i);
            }

        }

        static void PrintNumberWithDelay()
        { 
            Console.WriteLine("Starting....");
            for (int i = 0; i <= 10; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(2));
                Console.WriteLine(i);
            }
        }

1、创建线程

 Thread t = new Thread(PrintNumberWithDelay);
            t.Start();

2、暂停线程

Thread.Sleep(TimeSpan.FromSeconds(6));

3、终止线程

 Thread t = new Thread(PrintNumberWithDelay);
            t.Start();
            Thread.Sleep(TimeSpan.FromSeconds(6));
            t.Abort(); // 终止线程, 不推荐

4、线程等待

          Thread t = new Thread(PrintNumberWithDelay);
            t.Start();
            Thread.Sleep(TimeSpan.FromSeconds(6));
           //线程等待 
            t.Join();
            Console.WriteLine("Thread complated");
            PrintNumbers();
            Console.ReadLine();

5、线程优先级

Thread t = new Thread(PrintNumberWithDelay);
            t.Name = "tt";
            t.Priority = ThreadPriority.BelowNormal;

6、后台线程

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

namespace ConsoleApp1
{
    internal class ThreadSample
    {
        private readonly int _iterations;

        public ThreadSample(int iterations)
        { 
            _iterations = iterations;
        }

        public void CountNumbers()
        {
            for (int i = 1; i < _iterations; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine("{0} prints {1}",Thread.CurrentThread.Name,i);
            }
        }
    }
}

 static void Main(string[] args)
        {
            var sampleForeground = new ThreadSample(10);
            var sampleBackground = new ThreadSample(20);
            var threadOne = new Thread(sampleForeground.CountNumbers);
            threadOne.Name = "FOREGROUND";
            var threadTwo = new Thread(sampleBackground.CountNumbers);
            threadTwo.Name = "BACKGROUND";
            threadTwo.IsBackground = true;
            threadOne.Start();
            threadTwo.Start();
        }

 7、线程参数

在创建线程之后,可以使用start(object) 方法接受一个参数。这个参数就是线程参数。只可以接受一个参数,如果要传递的数据较多,则需要对数据进行封装

8、lock

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

namespace ConsoleApp1.Model
{
    abstract class CounterBase
    {
        public abstract void Increment();
        public abstract void Decrement();
    }

    class Counter : CounterBase
    {
        public int Count { get; private set; }
        public override void Decrement()
        {
            Count++;
        }

        public override void Increment()
        {
            Count--;
        }
    }

    class CounterWithLock : CounterBase
    {
        private readonly object lockObject = new object();
        public int Count { get; private set; }
        public override void Decrement()
        {
            lock (lockObject) { Count++; }
            
        }

        public override void Increment()
        {
           lock(lockObject) { Count--; }
        }
    }
}
  static void Main(string[] args)
        {
           

            var c = new Counter();
            var t1 = new Thread(() =>TestCounter(c));
            var t2 = new Thread(() => TestCounter(c));
            var t3 = new Thread(() => TestCounter(c));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
             Console.WriteLine("--------------{0}-----------------",c.Count);

            var c1 = new CounterWithLock();
            t1 = new Thread(() => TestCounter(c1));
            t2 = new Thread(() => TestCounter(c1));
            t3 = new Thread(() => TestCounter(c1));
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("--------------{0}-----------------", c1.Count);
            Console.ReadLine();
        }

        static void TestCounter(CounterBase c)
        {
            for (int i = 0; i < 100000; i++)
            {
                c.Increment();
                c.Decrement();
            }
        }

 使用lock 可能出现死锁

9、Monitor


        static void LockTooMuch(object lock1, object lock2)
        {
            lock (lock1)
            {
                Thread.Sleep(1000);
                lock (lock2);
            }
        }
        static void Main(string[] args)
        {
            object lock1 = new object();
            object lock2 = new object();
            new Thread(()=>LockTooMuch(lock1, lock2)).Start();
            lock (lock2)
            {
                Thread.Sleep(1000);
                if (Monitor.TryEnter(lock1, TimeSpan.FromSeconds(5)))
                {
                    Console.WriteLine("请求受保护的资源完成");
                }
                else
                {
                    Console.WriteLine("请求资源超时");
                }
            }
            new Thread(() => LockTooMuch(lock1, lock2)).Start();
            lock (lock2)
            {
                Thread.Sleep(1000);
                lock (lock1)
                {
               
                    Console.WriteLine("请求资源成功");
                }
            }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值