溫馨提示×

c#中synchronized的用法是什么

c#
小億
139
2024-05-30 14:36:11
欄目: 編程語言

在C#中,可以使用關(guān)鍵字synchronized來實(shí)現(xiàn)線程同步,保證多個線程訪問共享資源時的安全性。在C#中,synchronized關(guān)鍵字可以通過lock關(guān)鍵字來實(shí)現(xiàn)。在lock關(guān)鍵字的作用域內(nèi),只有一個線程可以訪問共享資源,其他線程必須等待當(dāng)前線程執(zhí)行完畢才能訪問。

下面是一個使用synchronized關(guān)鍵字實(shí)現(xiàn)線程同步的示例代碼:

using System;
using System.Threading;

class Program
{
    private static object lockObj = new object();

    static void Main()
    {
        Thread t1 = new Thread(DoWork);
        Thread t2 = new Thread(DoWork);

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine("All threads have finished.");
    }

    static void DoWork()
    {
        lock (lockObj)
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} is working.");
                Thread.Sleep(100);
            }
        }
    }
}

在上面的示例中,定義了一個靜態(tài)對象lockObj作為鎖對象,然后在DoWork方法中使用lock關(guān)鍵字對共享資源進(jìn)行同步操作。這樣可以確保多個線程訪問共享資源時的安全性。

0