Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace ThreadingLesson
- {
- class ThreadExample
- {
- private int _counter;
- private bool _exit;
- Thread countThread;
- Thread displayThread;
- Thread inputThread;
- Thread overloadThread;
- //Konstruktor
- public ThreadExample()
- {
- _counter = 0;
- _exit = false;
- //Inicjowanie wątków
- countThread = new Thread(new ThreadStart(Counting));
- displayThread = new Thread(new ThreadStart(Displaying));
- inputThread = new Thread(new ThreadStart(InputReading));
- overloadThread = new Thread(new ThreadStart(OverloadThread));
- }
- public void RunThreads()
- {
- //Rozpoczęcie działania wątków
- countThread.Start();
- displayThread.Start();
- inputThread.Start();
- //Uwaga, zwiększa użycie procesora do 100%
- //overloadThread.Start();
- }
- private void Counting()
- {
- while(!_exit)
- {
- _counter++;
- Thread.Sleep(1000);
- }
- }
- private void Displaying()
- {
- while(!_exit)
- {
- Console.SetCursorPosition(0, 0);
- Console.WriteLine("Stan licznika: " + _counter.ToString());
- }
- }
- private void InputReading()
- {
- //Niestandardowy for - zmienia wartość pause na przemian,
- //działa dopóki !_exit, jak pozostałe
- for(bool pause = false; !_exit; pause = !pause)
- {
- Console.ReadLine();
- if(pause)
- countThread.Suspend();
- else
- countThread.Resume();
- }
- }
- //Metoda do zabawy w przeciążanie wątku
- private void OverloadThread()
- {
- while(true)
- {
- try
- {
- overloadThread = new Thread(new ThreadStart(OverloadThread));
- overloadThread.Start();
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex);
- }
- }
- }
- }
- public class Program
- {
- public static void Main(string[] args)
- {
- ThreadExample example = new ThreadExample();
- example.RunThreads();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement