Skip to content

Instantly share code, notes, and snippets.

@peterthorsteinson
Created October 12, 2019 04:21
Show Gist options
  • Save peterthorsteinson/50206edb06acce46f9a9c09dfb6067e3 to your computer and use it in GitHub Desktop.
Save peterthorsteinson/50206edb06acce46f9a9c09dfb6067e3 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
Thread[] threadArray = new Thread[8];
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.Red);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.Yellow);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.Magenta);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.Green);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.White);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.Blue);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.Cyan);
(threadArray[0] = new Thread(ThreadFunc)).Start(ConsoleColor.DarkGreen);
for (int i = 0; i < threadArray.Length; i++) threadArray[i].Join();
}
public static void ThreadFunc(object data)
{
int width = 120;
int height = 60;
int x = rand.Next(width);
int y = rand.Next(height);
int deltaX = rand.Next(-3, 4);
int deltaY = rand.Next(-3, 4);
while (true)
{
lock (lockObject)
{
Console.CursorVisible = false;
Console.ForegroundColor = (ConsoleColor)data;
Console.SetCursorPosition(x, y);
Console.Write(' ');
int tempX = x + deltaX;
if (tempX < 0) { deltaX = -deltaX; continue; }
if (tempX >= width) { deltaX = -deltaX; continue; }
int tempY = y + deltaY;
if (tempY < 0) { deltaY = -deltaY; continue; }
if (tempY >= height) { deltaY = -deltaY; continue; }
x = tempX;
y = tempY;
Console.SetCursorPosition(x, y);
Console.Write('*');
}
Thread.Sleep(100);
}
}
public static Random rand = new Random();
private static readonly object lockObject = new object();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment