C#中 Thread类的使用

本文介绍了C#中Thread类的基本使用,包括工作函数、start和join。同时探讨了Mutex和Monitor两种线程同步互斥的方法,特别强调了Monitor与对象的关联性以及在多线程操作同一队列时的保护作用。通过示例展示了如何在并发环境下确保数据操作的完整性和一致性。
摘要由CSDN通过智能技术生成

基本的 Thread 框架

基本的 Thread 程序结构,由工作函数,start 和 join 组成

Thread类是比较常用的一个类,这里总结了一些基本的使用方法和程序示例,以备以后查用。


https://msdn.microsoft.com/zh-cn/library/system.threading.thread.aspx


using System;
using System.Threading;

// Simple threading scenario:  Start a static method running
// on a second thread.
public class ThreadExample
{
    // The ThreadProc method is called when the thread starts.
    // It loops ten times, writing to the console and yielding 
    // the rest of its time slice each time, and then ends.
    public static void ThreadProcA()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("ThreadProc A: {0}", i);
            Thread.Sleep(0);
        }
    }

    public static void ThreadProcB()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("ThreadProc B: {0}", i);
            // Yield the rest of the time slice.
            Thread.Sleep(0);
        }
    }


    public static void Main()
    {
        Console.WriteLine("Main thread: Start a second thread.");
        // The constructor for the Thread class requires a ThreadStart 
        // delegate that represents the method to be executed on the 
        // thread.  C# simplifies the creation of this delegate.
        Thread t = new Thread(new ThreadStart(ThreadProcA));
        Thread t1 = new Thread(new ThreadStart(ThreadProcB));

        // Start ThreadProc.  Note that on a uniprocessor, the new 
        // thread does not get any processor time until the main thread 
        // is preempted or yields.  Uncomment the Thread.Sleep that 
        // follows t.Start() to see the difference.
        t.Start();
        t1.Start();
        //Thread.Sleep(0);

        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine("Main thread: Do some work.");
            Thread.Sleep(0);
        }

        Console.WriteLine("Main thread: Call Join(), to wait until ThreadProc ends.");
        t.Join();
        t1.Join();

        Console.WriteLine("Main thread: ThreadProc.Join has returned.  Press Enter to end program.\n");
        Console.ReadLine();
    }
}

这仅仅是一个创建两个线程的例子,但并不太符合实际应用的情况

此时的输出结果A 与 B 随机打印。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值