Multi Threaded Printing (Synchronizing Threads) : lock « Thread « C# / CSharp Tutorial






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

public class Printer {
    public void PrintNumbers() {
        lock (this) {
            Console.WriteLine("-> {0} is executing PrintNumbers()", Thread.CurrentThread.Name);
            Console.Write("Your numbers: ");
            for (int i = 0; i < 10; i++) {
                Random r = new Random();
                Thread.Sleep(1000 * r.Next(5));
                Console.Write(i + ", ");
            }
            Console.WriteLine();
        }
    }
}

class Program {
    static void Main(string[] args) {
        Printer p = new Printer();
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new Thread(new ThreadStart(p.PrintNumbers));
            threads[i].Name = string.Format("Worker thread #{0}", i);
        }
        foreach (Thread t in threads)
            t.Start();
        Console.ReadLine();
    }
}








20.15.lock
20.15.1.Shared resource without lock
20.15.2.Lock Demo
20.15.3.Use lock to synchronize access to an object
20.15.4.Use of volatile: lock singleton
20.15.5.Using Lock
20.15.6.Use the lock object
20.15.7.Multi Threaded Printing (Synchronizing Threads)