Multithreading (basic article 2) and multithreading (basic article 2)

Source: Internet
Author: User

Multithreading (basic article 2) and multithreading (basic article 2)

In the previous multi-thread (basic Article 1), we mainly talked about how to create a thread, abort a thread, wait for a thread, and terminate a thread, in this article, we will continue to describe some knowledge about threads.

5. Determine the thread status

This section describes how to view the status of a thread. It is useful to know the status of a thread. However, the thread runs independently and its status may change at any time. To view the status of a thread, follow these steps:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click the "Program. cs" file and modify it to the following code:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5  6 namespace Recipe05 7 { 8     class Program 9     {10         static void DoNothing()11         {12             Sleep(TimeSpan.FromSeconds(2));13         }14 15         static void PrintNumbersWithStatus()16         {17             WriteLine("Starting...");18             WriteLine(CurrentThread.ThreadState.ToString());19 20             for(int i = 1; i < 10; i++)21             {22                 Sleep(TimeSpan.FromSeconds(2));23                 WriteLine(i);24             }25         }26 27         static void Main(string[] args)28         {29             WriteLine("Starting program...");30 31             Thread t1 = new Thread(PrintNumbersWithStatus);32             Thread t2 = new Thread(DoNothing);33 34             WriteLine(t1.ThreadState.ToString());35 36             t2.Start();37             t1.Start();38 39             for(int i = 1; i < 30; i++)40             {41                 WriteLine(i.ToString() + " - " + t1.ThreadState.ToString());42             }43 44             Sleep(TimeSpan.FromSeconds(6));45 46             t1.Abort();47 48             WriteLine("A thread has been aborted");49             WriteLine(t1.ThreadState.ToString());50             WriteLine(t2.ThreadState.ToString());51         }52     }53 }

3. Run the console application. The running effect may be different each time, as shown in:

In the above Code, we define two different threads t1 and t2 in the "Main" method. The t1 thread is terminated during execution and the t2 thread is successfully executed. We can use the ThreadState attribute of the Thread object to obtain the state information of a Thread. The ThreadState attribute is of the C # Enumeration type.

When the program runs at the second line of code, the t1 thread is not executed yet. At this time, the t1 thread status is "ThreadState. Unstarted ".

When the program runs at the second line of code, thread t1 starts to execute. The thread status is "ThreadState. Running ".

When running to 39th ~ When there are 42 lines of code, the main Thread starts to execute the loop statement and continuously prints the status of 29 t1 threads, because "Thread. sleep "method, so in the process of executing the main thread loop, the status of thread t1 is" ThreadState. running and ThreadState. waitSleepJoin.

When the program executes the Code in line 44th, the "Thread. sleep "method, while waiting for 6 seconds, the for loop code in the" PrintNumbersWithStatus "method is continuously executed, so three rows of numbers 1, 2, and 3 are printed.

When the program runs at line 1 of code, we call the "Abort" method of t1 to terminate the t1 thread.

When the program executes the code at line 1, the "Abort" method has been called on the t1 thread, so its status is "ThreadState. aborted or ThreadState. abortRequested ".

When the program runs at the second line of code, the status of the t2 thread is "ThreadState. Stopped" because the t2 thread is successfully executed ".

6. thread priority

In this section, we will talk about the thread priority, which determines the CPU time that the thread can use. Follow these steps to learn the thread priority:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click the "Program. cs" file and modify the Code as follows:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5 using static System.Diagnostics.Process; 6  7 namespace Recipe06 8 { 9     class ThreadSample10     {11         private bool isStopped = false;12 13         public void Stop()14         {15             isStopped = true;16         }17 18         public void CountNumbers()19         {20             long counter = 0;21             while (!isStopped)22             {23                 counter++;24             }25 26             WriteLine($"{CurrentThread.Name} with {CurrentThread.Priority,10} priority has a count = {counter,15:N0}");27         }28     }29 30     class Program31     {32         static void RunThreads()33         {34             var sample = new ThreadSample();35 36             var threadOne = new Thread(sample.CountNumbers);37             threadOne.Name = "ThreadOne";38 39             var threadTwo = new Thread(sample.CountNumbers);40             threadTwo.Name = "ThreadTwo";41 42             threadOne.Priority = ThreadPriority.Highest;43             threadTwo.Priority = ThreadPriority.Lowest;44 45             threadOne.Start();46             threadTwo.Start();47 48             Sleep(TimeSpan.FromSeconds(2));49             sample.Stop();50         }51 52         static void Main(string[] args)53         {54             WriteLine($"Current thread priority: {CurrentThread.Priority}");55             WriteLine("Running on all cores available");56 57             RunThreads();58 59             Sleep(TimeSpan.FromSeconds(2));60 61             WriteLine("Running on a single core");62             GetCurrentProcess().ProcessorAffinity = new IntPtr(1);63             RunThreads();64         }65     }66 }

3. Run the console application. The running effect may be different each time, as shown in:

In the above Code, we define two different threads threadOne and threadTwo. ThreadOne threads have the Highest priority "ThreadPriority. Highest", and threadTwo has the Lowest priority "ThreadPriority. Lowest ".

When the program runs to line 4 of code, if our computer is a multi-core computer, we will get the initial result within 2 seconds, the threadOne thread with the highest priority has more iterations than the threadTwo thread with the lowest priority, but it will not be too far apart. However, if our computer is a single-core computer, the results are very different.

To simulate a single-core computer, we set ProcessorAffinity to 1. Now the number of iterations of the two threads varies greatly, and the execution time of the program is far greater than 2 seconds. This is because most of the CPU's computer time is given to high-priority threads, while low-priority threads get very little CPU time.

VII. foreground and background threads

In this section, we will describe what the foreground thread and background thread are, and describe how to set this option to affect program behavior. Follow these steps to learn the foreground and background threads:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click the "Program. cs" file and modify the Code as follows:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5  6 namespace Recipe07 7 { 8     class ThreadSample 9     {10         private readonly int iterations;11 12         public ThreadSample(int iterations)13         {14             this.iterations = iterations;15         }16 17         public void CountNumbers()18         {19             for(int i = 0; i < iterations; i++)20             {21                 Sleep(TimeSpan.FromSeconds(0.5));22                 WriteLine($"{CurrentThread.Name} prints {i}");23             }24         }25     }26 27     class Program28     {29         static void Main(string[] args)30         {31             var sampleForeground = new ThreadSample(10);32             var sampleBackground = new ThreadSample(20);33 34             var threadOne = new Thread(sampleForeground.CountNumbers);35             threadOne.Name = "ForegroundThread";36 37             var threadTwo = new Thread(sampleBackground.CountNumbers);38             threadTwo.Name = "BackgroundThread";39             threadTwo.IsBackground = true;40 41             threadOne.Start();42             threadTwo.Start();43         }44     }45 }

3. Run the console application. The running effect may be different each time, as shown in:

In the above Code, we define two different threads threadOne and threadTwo. When we create a thread, it is displayed as a foreground thread, such as threadOne. To set a thread as a background thread, set the "IsBackground" attribute of the thread to "true", such as threadTwo. We also configured two threads to execute different cycles. The number of cycles executed by the threadOne thread is 10, and the number of cycles executed by the threadTwo thread is 20, therefore, the threadOne thread is executed earlier than the threadTwo thread.

From the execution result, when the threadOne thread finishes executing the program, the main program ends and the background thread is terminated. This is the difference between the foreground thread and the background thread: the process will not end until all foreground processes are completed.

8. Passing parameters to the thread

In this section, I will describe how to pass parameters to a thread. We will use different methods to complete this task. The specific steps are as follows:

1. Use Visual Studio 2015 to create a new console application.

2. Double-click the "Program. cs" file and modify the Code as follows:

 1 using System; 2 using System.Threading; 3 using static System.Console; 4 using static System.Threading.Thread; 5  6 namespace Recipe08 7 { 8     class ThreadSample 9     {10         private readonly int iterations;11 12         public ThreadSample(int iterations)13         {14             this.iterations = iterations;15         }16 17         public void CountNumbers()18         {19             for(int i = 1; i <= iterations; i++)20             {21                 Sleep(TimeSpan.FromSeconds(0.5));22                 WriteLine($"{CurrentThread.Name} prints {i}");23             }24         }25     }26 27     class Program28     {29         static void Count(object iterations)30         {31             CountNumbers((int)iterations);32         }33 34         static void CountNumbers(int iterations)35         {36             for(int i = 1; i <= iterations; i++)37             {38                 Sleep(TimeSpan.FromSeconds(0.5));39                 WriteLine($"{CurrentThread.Name} prints {i}");40             }41         }42 43         static void PrintNumber(int number)44         {45             WriteLine(number);46         }47 48         static void Main(string[] args)49         {50             var sample = new ThreadSample(10);51 52             var threadOne = new Thread(sample.CountNumbers);53             threadOne.Name = "ThreadOne";54             threadOne.Start();55             threadOne.Join();56 57             WriteLine("--------------------------");58 59             var threadTwo = new Thread(Count);60             threadTwo.Name = "ThreadTwo";61             threadTwo.Start(8);62             threadTwo.Join();63 64             WriteLine("--------------------------");65 66             var threadThree = new Thread(() => CountNumbers(12));67             threadThree.Name = "ThreadThree";68             threadThree.Start();69             threadThree.Join();70 71             WriteLine("--------------------------");72 73             int i = 10;74             var threadFour = new Thread(() => PrintNumber(i));75 76             i = 20;77             var threadFive = new Thread(() => PrintNumber(i));78 79             threadFour.Start();80             threadFive.Start();81         }82     }83 }

3. Run the console application. The running effect is shown in:

In 50th ~ In the 55-line code, we first created a ThreadSample type object and passed the number 10 to the constructor of this type. Then, we pass the "CountNumbers" method of the ThreadSample object to the threadOne constructor. The "CountNumbers" method will be executed in the threadOne thread, therefore, the number 10 is passed to the threadOne thread through the CountNumbers method.

In 59th ~ In 62 lines of code, we use "Thread. to make the code correctly run, we must ensure that when constructing a threadTwo thread, the delegate passed to the Thread constructor must contain an object-type parameter. In this Code, we regard 8 as an object and pass it to the "Count" method. This method calls the overload method of the same name to convert the object to the integer type.

In 66th ~ In 69 lines of code, when we create a threadThree Thread, we pass a lambda expression to the Thread constructor. This expression defines a method that does not belong to any class, in this lambda expression, we call the "CountNumbers" method and pass 12 to the "CountNumbers" method. Through the lambda expression, we pass 12 to the threadThree thread.

  Note:When we use a local variable for multiple lambda expressions, these lambda expressions will share the value of this variable between 73rd and ~ At line 80 of the code, we used local variables for two lambda expressions. After running the threadFour and threadFive threads, we found that the printed results were both 20.

Not complete to be continued!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.