multithreaded combat (i) Thread basics

Source: Internet
Author: User

The benefits of threading, I don't want to say that there are too many blog parks, but the individual on the thread to understand the basis, decided to take the learning thread (there are some examples of the blog Park):

Creating Threads

Pausing a thread

Waiting for thread

Line path Parameters

Lock

Monitor

Creating Threads
New Thread (printnumbers);//threads Create T. Start ();//Starting Thread
Printnumbers (); Static void printnumbers () { Console.WriteLine ("Starting ..."); for (int1; i++) { Console.WriteLine (i); }}

Pausing a thread

Sleep pauses the thread;

Thread T =NewThread (Printnumberswithdelay); T.start ();Static voidPrintnumberswithdelay () {Console.WriteLine ("starting ...");  for(inti =1; I <Ten; i++) {Thread.Sleep ( -); Console.WriteLine (string. Format ("Order {0}, Time: {1}", I, DateTime.Now)); }        }

Sleep (2000); output once every 2 seconds;

Waiting for thread
Thread T =NewThread (Run);        T.start (); //join is equivalent to embedding the Run method in thisT.join (); //damn it, T. Join (), my main thread must not be executed until you have finished executing it. Console.WriteLine ("I am the main thread:"+Thread.CurrentThread.GetHashCode ()); }    Static voidRun () {//Wait 5sThread.Sleep ( the); Console.WriteLine ("I am a thread:"+Thread.CurrentThread.GetHashCode ()); }

Line path Parameters
 varThreadone =NewThread (one); Threadone.start (" One");            Threadone.join (); varThreadtwo =NewThread (() = one (" Both"));            Threadtwo.start ();            Threadtwo.join (); varValue ="three"; varThreadthree =NewThread (() =One (value)); Value=" Four"; varThreadfour =NewThread (() =One (value));            Threadthree.start (); Threadfour.start ();Static voidOne (Objectobj)        {Console.WriteLine (obj); }

At startup thread 3, 4 o'clock, the value of the variable value becomes four, and finally prints out four

Lock

Console.WriteLine ("Irregular Statistics"); varc =NewCounter (); varT1 =NewThread (() =Testcounter (c)); vart2 =NewThread (() =Testcounter (c)); varT3 =NewThread (() =Testcounter (c)); T1.            Start (); T2.            Start (); T3.            Start (); T1.            Join (); T2.            Join (); T3.            Join (); Console.WriteLine ("total: {0}", C.count); Console.WriteLine ("--------------------------"); Console.WriteLine ("Correct statistics"); varC1 =NewCounterwithlock (); T1=NewThread (() =Testcounter (C1)); T2=NewThread (() =Testcounter (C1)); T3=NewThread (() =Testcounter (C1)); T1.            Start (); T2.            Start (); T3.            Start (); T1.            Join (); T2.            Join (); T3.            Join (); Console.WriteLine ("total: {0}", C1. Count);Static voidTestcounter (counterbase c) { for(inti =0; I <100000; i++) {c.increment ();            C.decrement (); }        }        classCounter:counterbase { Public intCount {Get;Private Set; }  Public Override voidIncrement () {Count++; }             Public Override voidDecrement () {Count--; }        }        classCounterwithlock:counterbase {Private ReadOnly Object_syncroot =NewObject ();  Public intCount {Get;Private Set; }  Public Override voidIncrement () {Lock(_syncroot) {Count++; }            }             Public Override voidDecrement () {Lock(_syncroot) {Count--; }            }        }        Abstract classCounterbase { Public Abstract voidIncrement ();  Public Abstract voiddecrement (); }

The results of locking and non-locking statistics are completely different.

Monitor

Synchronous access to the object mechanism; only one thread is allowed to access in the locked critical section, and other threads are queued for waiting.

1:monitor.enter and Monitor.Exit

  for(inti =0; I <Ten; i++) {Thread T=NewThread (Run);            T.start (); }//Resources        Static Objectobj =New Object(); Static intCount =0; Static voidRun () {Thread.Sleep (Ten); //Enter the critical sectionMonitor.Enter (obj); Console.WriteLine ("Current number: {0}", ++count); //Exit critical Sectionmonitor.exit (obj); }

2:monitor.wait and Monitor.pulse

Wait: Temporarily frees the resource lock, and then the thread enters the wait queue, so the natural thread can get the resource lock.

Pulse: Wake up the thread in the wait queue, then the thread that was waited on was re-acquired to the lock.

  Public classProgram { Public Static voidMain (string[] args) {Lockobj obj=Newlockobj (); //Note that the same resource object obj is used hereJack Jack =NewJack (obj); John John=NewJohn (obj); Thread T1=NewThread (NewThreadStart (Jack.            Run)); Thread T2=NewThread (NewThreadStart (John.            Run)); T1.            Start (); T1. Name="Jack"; T2.            Start (); T2. Name="John";        Console.ReadLine (); }    }    //Lock Object     Public classLockobj {} Public classJack {PrivateLockobj obj;  PublicJack (Lockobj obj) { This. obj =obj; }         Public voidRun () {Monitor.Enter ( This. obj); Console.WriteLine ("{0}: I have entered the latrine. ", Thread.CurrentThread.Name); Console.WriteLine ("{0}: Rub, too smelly, I still withdraw! ", Thread.CurrentThread.Name); //Temporary release lock resourceMonitor.Wait ( This. obj); Console.WriteLine ("{0}: The brothers are right, I'll go in. ", Thread.CurrentThread.Name); //Wake up threads in the wait queueMonitor.pulse ( This. obj); Console.WriteLine ("{0}: It's good to be finished. ", Thread.CurrentThread.Name); Monitor.Exit ( This. obj); }    }     Public classJohn {PrivateLockobj obj;  PublicJohn (Lockobj obj) { This. obj =obj; }         Public voidRun () {Monitor.Enter ( This. obj); Console.WriteLine ("{0}: Go straight to the latrine, brother, you should come in, be careful to suppress the bad! ", Thread.CurrentThread.Name); //Wake up threads in the wait queueMonitor.pulse ( This. obj); Console.WriteLine ("{0}: Hua-hua ....", Thread.CurrentThread.Name); //Temporary release lock resourceMonitor.Wait ( This. obj); Console.WriteLine ("{0}: It's good to be finished. ", Thread.CurrentThread.Name); Monitor.Exit ( This. obj); }    }

multithreaded combat (i) Thread basics

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.