Untitled

mail@pastecode.io avatar
unknown
plain_text
10 days ago
1.8 kB
2
Indexable
Never
using System;
using System.Threading;

class Program
{
    private static readonly object _lock = new object();
    private static int _currentNumber = 1;
    private static bool _ascending = true;
    private const int MaxNumber = 10;

    static void Main()
    {
        Thread[] threads = new Thread[MaxNumber];

        for (int i = 1; i <= MaxNumber; i++)
        {
            int threadNumber = i;
            threads[threadNumber - 1] = new Thread(() => PrintNumber(threadNumber));
            threads[threadNumber - 1].Start();
        }

        foreach (var thread in threads)
        {
            thread.Join();
        }
    }

    static void PrintNumber(int number)
    {
        while (true)
        {
            lock (_lock)
            {
                while (number != _currentNumber)
                {
                    Monitor.Wait(_lock);
                }

                Console.WriteLine(number);

                if (_ascending)
                {
                    if (_currentNumber == MaxNumber)
                    {
                        _ascending = false;
                        _currentNumber--;
                    }
                    else
                    {
                        _currentNumber++;
                    }
                }
                else
                {
                    if (_currentNumber == 1)
                    {
                        _ascending = true;
                        _currentNumber++;
                    }
                    else
                    {
                        _currentNumber--;
                    }
                }

                Monitor.PulseAll(_lock);
            }

            Thread.Sleep(100); // Bu satır, CPU kullanımını azaltmak için eklenmiştir.
        }
    }
}
Leave a Comment