Multithreading programming learning notes-basics (2), multithreading programming learning notes

Source: Internet
Author: User

Multithreading programming learning notes-basics (2), multithreading programming learning notes
Multi-thread programming learning notes-basics (1) 5. terminate a thread (Abort)

1. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread namespace ThreadConsoleApp {class Program {static void Main (string [] args) {Console. writeLine ("START"); Thread t = new Thread (PrintNumberDely); // start Thread t. start (); Thread. sleep (TimeSpan. fromSeconds (6); // thread termination t. abort (); Console. writeLine ("thread termination"); Console. writeLine ("start a new Thread"); t = new Thread (PrintNumber); t. Start (); PrintNumber (); Console. Read ();} static void PrintNumber () {Console. WriteLine ("The fourth multithreading program starts .... Second: "+ DateTime. now. second); for (int I = 0; I <10; I ++) {Console. writeLine (string. format ("{0}", I) ;}/// <summary> /// Method for suspending 2 seconds /// </summary> static void PrintNumberDely () {Console. writeLine ("the first multi-thread termination program starts .... "); For (int I = 0; I <10; I ++) {Console. writeLine (string. format ("Second: {0 }=={ 1}", DateTime. now. second, I); Thread. sleep (TimeSpan. fromSeconds (2 ));}}}}

2. The program execution result is as follows:

 

From the results, we can see that the program first started the print numeric method of the sub-thread. After six seconds of running, the abort method was called to terminate the sub-thread. However, this abort is injected with the ThreadAbortException method to terminate with the thread. This method is very dangerous and is not recommended. After the sub-thread is terminated, the main thread continues to run.

 

6. ThreadState)

1. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread namespace ThreadConsoleApp {class Program {static void Main (string [] args) {Console. writeLine ("START"); Thread t = new Thread (PrintNumberStatus); Thread t2 = new Thread (DoNothing); // start Thread t2.Start (); t. start (); // display the Thread status for (int I = 0; I <10; I ++) {Thread. sleep (TimeSpan. fromMilliseconds (300); Console. writeLine (t. threadState. toString ();} Thread. sleep (TimeSpan. fromSeconds (4); // thread termination t. abort (); Console. writeLine ("thread termination"); Console. writeLine (string. format ("t thread status: {0}", t. threadState. toString (); Console. writeLine (string. format ("t2 thread status: {0}", t2.ThreadState. toString (); Console. read ();} static void DoNothing () {Console. writeLine ("the fifth multi-threaded program starts .... Second: "+ DateTime. now. second); Thread. sleep (TimeSpan. fromSeconds (2);} // <summary> // Method for suspending 2 seconds /// </summary> static void PrintNumberStatus () {Console. writeLine ("the fifth multi-thread Detection State program starts .... "+ Thread. currentThread. threadState. toString (); for (int I = 0; I <10; I ++) {Console. writeLine (string. format ("Second: {0 }=={ 1}", DateTime. now. second, I); Thread. sleep (TimeSpan. fromSeconds (2 ));}}}}

2. The program execution result is as follows:

 

For example, when the main thread starts, two subthreads are defined. One thread is terminated, and the other thread is running until the end. After the thread is started, the status of the t2 thread changes to Running, and then to WaitSleepJoin until the Running ends and changes to Stopped. The other t thread prints a number. When we call the abort method, the t thread status changes to AbortRequested. This fully demonstrates the complexity of synchronizing two threads. Do not use abort in the program to terminate the thread.


7. thread Priority (Priority)

1. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread using System. diagnostics; namespace ThreadConsoleApp {class Program {static void Main (string [] args) {Console. writeLine ("START, priority of the current Thread:" + Thread. currentThread. priority); Console. writeLine ("Thread running multi-core CPU"); // start the Thread Run (); Thread. sleep (TimeSpan. fromSeconds (2); // simulates the Console on a single core. writeLine ("the thread runs a single-core CP U on "); Process. getCurrentProcess (). processorAffinity = new IntPtr (1); Run (); Console. read ();} static void Run () {var demo = new ThreadRunDemo (); Thread thread1 = new Thread (demo. countNumber); thread1.Name = "ThreadOne"; Thread thread2 = new Thread (demo. countNumber); thread2.Name = "ThreadTwo"; thread2.Priority = ThreadPriority. belowNormal; Thread thread3 = new Thread (demo. countNumber); thread3.Na Me = "ThreadThree"; thread1.Priority = ThreadPriority. highest; thread2.Priority = ThreadPriority. aboveNormal; thread3.Priority = ThreadPriority. lowest; thread1.Start (); thread2.Start (); thread3.Start (); Thread. sleep (2000); demo. stop () ;}} class ThreadRunDemo {private bool isStopped = false; public void Stop () {isStopped = true;} public void CountNumber () {long cnt = 0; while (! IsStopped) {cnt ++;} Console. WriteLine (string. Format ("thread {0} priority {}, total calculated {} number ",
Thread. CurrentThread. Name, Thread. CurrentThread. Priority. ToString (), cnt. ToString ("N0 ")));}}}

2. The program execution result is as follows:

 

From the results, we can see that when a multi-threaded program runs on a multi-core CPU, the priority plays a little different role. As a result, the difference between the highest priority and the lowest priority is about 10%. If you run a multi-threaded program on a single-core CPU, the priority effect is particularly obvious. As a result, the difference between the highest priority and the lowest priority is over 100 times.


8. foreground and background threads

1. The Code is as follows:

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading; // introduce the thread using System. diagnostics; namespace ThreadConsoleApp {class Program {static void Main (string [] args) {Console. writeLine ("START, foreground Thread and background Thread"); var fore = new ThreadBackground (10); var back = new ThreadBackground (20); Thread threadF = new Thread (fore. countNumber); threadF. name = "foreground Thread"; Thread ThreadB = new Thread (back. countNumber); threadB. name = "background thread"; threadB. isBackground = true; // start the thread threadF. start (); threadB. start (); // Console. read () ;}} class ThreadBackground {private int cnt; public ThreadBackground (int count) {cnt = count;} public void CountNumber () {for (int I = 0; I <cnt; I ++) {Thread. sleep (1, 500); Console. writeLine (string. format ("Thread {0} print number {}", Thread. currentT Hread. Name, I. ToString ("N0");} Console. WriteLine ("{0} finished counting.", Thread. CurrentThread. IsBackground? "Background Thread": "Foreground Thread ");}}}

2. program execution results

 

According to the above Code, when the program is executed, it will flash and exit. This is because the execution of the foreground thread has ended. Although the background thread has not ended, the program will automatically terminate the background thread. This is the difference between the foreground thread and the background thread. The process will wait for all the foreground threads to complete the execution. If only the background threads are not completed, the work will be completed directly.


Related Article

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.