.Net多线程Threading相关详解

一、线程不安全例子

计数

cs 复制代码
const int total = 100_000;

int count = 0;

var thread1 = new Thread(Increment);
var thread2 = new Thread(Increment);

thread1.Start();
thread2.Start();

thread1.Join();
thread2.Join();

Console.WriteLine($"Count: {count}");

void Increment()
{
    for (int i = 0; i < total; i++)
        count++;
}

操作队列

cs 复制代码
var queue = new Queue<int>();

var producer = new Thread(Producer);
var consumer1 = new Thread(Consumer);
var consumer2 = new Thread(Consumer);

producer.Start();
consumer1.Start();
consumer2.Start();

producer.Join();
Thread.Sleep(100); // Wait for consumers to finish

consumer1.Interrupt();
consumer2.Interrupt();
consumer1.Join();
consumer2.Join();

void Producer()
{
    for (int i = 0; i < 20; i++)
    {
        Thread.Sleep(20);
        queue.Enqueue(i);
    }
}

void Consumer()
{
    try
    {
        while (true)
        {
            if (queue.TryDequeue(out var res))
                Console.WriteLine(res);
            Thread.Sleep(1);
        }
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("Thread interrupted.");
    }
}

二、Parallel与PLINQ

cs 复制代码
var inputs = Enumerable.Range(1,20).ToArray();

int HeavyJob(int input)
{
    Thread.Sleep(300);
    return input;
}

// Sequential
var forOutputs = new int[inputs.Length];
for (int i = 0; i < inputs.Length; i++)
{
    forOutputs[i] = HeavyJob(inputs[i]);
}

// Parallel
var parallelOutputs = new int[inputs.Length];
Parallel.For(0, inputs.Length, i =>
{
    parallelOutputs[i] = HeavyJob(inputs[i]);
});

// PLINQ
var plinqOutputs = inputs.AsParallel().Select(HeavyJob).ToArray();

三、PLINQ 与信号量

cs 复制代码
using System.Diagnostics;

var inputs = Enumerable.Range(1,20).ToArray();
var semaphore = new Semaphore(3, 3);

int HeavyJob(int input)
{
    semaphore.WaitOne();
    Thread.Sleep(300);
    semaphore.Release();
    return input;
}

var sw = Stopwatch.StartNew();
var plinqOutputs = inputs.AsParallel().Select(HeavyJob).ToArray();
sw.Stop();
Console.WriteLine($"Elapsed time: {sw.ElapsedMilliseconds}ms");

四、线程终止

cs 复制代码
//线程终止
var thread = new Thread(() =>
{
    try
    {
        for (int i = 0; i < 10; i++)
        {
            Thread.Sleep(1000);
            Console.WriteLine("Sub thread: " + i);
        }
    }
    catch (ThreadInterruptedException)
    {
        Console.WriteLine("Thread interrupted");
    }
});

thread.Start();
Thread.Sleep(3500);
thread.Interrupt();
thread.Join();
Console.WriteLine("Done");
相关推荐
mghio7 小时前
Dubbo 中的集群容错
java·微服务·dubbo
咖啡教室12 小时前
java日常开发笔记和开发问题记录
java
咖啡教室12 小时前
java练习项目记录笔记
java
鱼樱前端13 小时前
maven的基础安装和使用--mac/window版本
java·后端
RainbowSea13 小时前
6. RabbitMQ 死信队列的详细操作编写
java·消息队列·rabbitmq
RainbowSea13 小时前
5. RabbitMQ 消息队列中 Exchanges(交换机) 的详细说明
java·消息队列·rabbitmq
我不会编程55515 小时前
Python Cookbook-5.1 对字典排序
开发语言·数据结构·python
李少兄15 小时前
Unirest:优雅的Java HTTP客户端库
java·开发语言·http
此木|西贝15 小时前
【设计模式】原型模式
java·设计模式·原型模式