-
-
Save OlegJakushkin/9714b3ee660739936927 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Collections.Generic; | |
using System.Linq; | |
public class Animal{ | |
public string Name; | |
public object Mutex = new object(); | |
} | |
public class Panda: Animal | |
{ | |
public void Chew() | |
{ | |
Console.WriteLine(String.Format("{0}: Nama-nama!", Name)); | |
} | |
public void Sleap() | |
{ | |
Console.WriteLine(String.Format("{0}: Z-z-z!", Name)); | |
} | |
public void Pat() | |
{ | |
Console.WriteLine(String.Format("{0}: Ur-Ur-Ur!", Name)); | |
} | |
public void Live() | |
{ | |
for (var i = 0; i < 50; ++i) | |
{ | |
lock (Mutex) | |
{ | |
Sleap(); | |
Thread.Sleep(100); | |
Chew(); | |
} | |
} | |
} | |
} | |
public class Park | |
{ | |
private readonly List<Panda> pandas = new List<Panda>(); | |
private readonly List<Thread> threads = new List<Thread>(); | |
public Park() | |
{ | |
for(var i = 0; i < 99; ++i) { | |
pandas.Add(new Panda() | |
{ | |
Name = i.ToString() | |
}); | |
} | |
pandas.ForEach( | |
panda => { | |
var t = new Thread(() => panda.Live()); | |
threads.Add(t); | |
t.Start(); | |
}); | |
} | |
public void GetPanda() { | |
var panda = pandas.First(p => p.Name == "15" ); | |
lock (panda.Mutex) | |
{ | |
panda.Pat(); | |
} | |
} | |
} | |
namespace ThreadingExamples | |
{ | |
static class Programm | |
{ | |
static void Main() | |
{ | |
var p = new Park(); | |
while (true) | |
{ | |
p.GetPanda(); | |
} | |
Console.ReadKey(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment