using System; using System.Threading; // namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Thread myThread = new Thread(func); // (Thread) myThread.Start(); // for (int i = 0; i < 10; i++ ) { Console.WriteLine(" 1 " + i); Thread.Sleep(0); } Console.Read(); // } // static void func() { for (int i = 0; i < 10; i++) { Console.WriteLine(" 2 " + i.ToString()); Thread.Sleep(0); }
What you should pay attention to in this program. Primarily this is the System.Threading namespace. This namespace contains classes that support multi-threaded programming. And it is there that contains the class Thread , which we use later in the code. Thread myThread = new Thread(func);
myThread.IsBackground = false;
However, we do not need to create a new thread inside the Main method. Let's create a class that will open a new thread in its own constructor. The class created by us will continue to deal with the account, but this time it will count to the specified number, due to the transfer of parameters to the stream. using System; using System.Threading; namespace ConsoleApplication1 { class Program { class myThread { Thread thread; public myThread(string name, int num) // { thread = new Thread(this.func); thread.Name = name; thread.Start(num);// } void func(object num)// , { for (int i = 0;i < (int)num;i++ ) { Console.WriteLine(Thread.CurrentThread.Name + " " + i); Thread.Sleep(0); } Console.WriteLine(Thread.CurrentThread.Name + " "); } } static void Main(string[] args) { myThread t1 = new myThread("Thread 1", 6); myThread t2 = new myThread("Thread 2", 3); myThread t3 = new myThread("Thread 3", 2); Console.Read(); } } }
Let us consider this example. The constructor of our myThread class takes 2 parameters: a string in which we define the name of the stream, and the number to which the count will be kept in the loop. In the constructor, we create a stream associated with the func function of this object. Next, we assign a name to our stream using the Name field of the created stream. And we start our thread by passing the Start function an argument.Source: https://habr.com/ru/post/126495/
All Articles