Q:

C# program to demonstrate thread lock

0

C# program to demonstrate thread lock

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

/*
 *  Demonstrate thread lock using C# program
 */
 
using System;
using System.Threading;
 
class LockDemo
{
    static readonly object _object = new object();
 
    static void ThreadMethod()
    {
        lock (_object)
        {
            Thread.Sleep(100);
            Console.WriteLine(DateTime.Now);
        }
    }
    static void Main()
    {
        int loop = 0;

        while (loop < 5)
        {
            ThreadStart T = new ThreadStart(ThreadMethod);
            new Thread(T).Start();
            loop++;
        }
    }
}

Output:

8/13/2020 8:14:54 PM
8/13/2020 8:14:54 PM
8/13/2020 8:14:55 PM
8/13/2020 8:14:55 PM
8/13/2020 8:14:55 PM
Press any key to continue . . .

Explanation:

In the above program, we created a LockDemo class that contains two static methods ThreadMethod() and Main(). In the ThreadMethod(), we used mutual exclusive lock using lock keyword and Thread.Sleep() method is used to pause the thread execution. In the Main() method we created threads in the while loop.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now