About multithreaded Vernacular edition

Source: Internet
Author: User

Multi-Threading is the problem that programmers often face frequently, the mastery and comprehension level of multithreading concept will also be used by some veteran to measure an important reference index of a person's programming strength. Whether it is the actual work needs or to meet the interview, mastering multithreading is a must pass in the programmer's career. In fact, when you put "multi-threaded" and your "career" to consider the time, you will feel "multithreading" is how small, right, there is no crossing mountains. But even if it is small, it is possible to change the trajectory of your life. Don't worry, if you're not familiar with multithreading, then let's take a look at what multithreading is.

In front of a few styles, I will give a real-life example at the beginning, through this example to map some of the obscure and boring computer programming expertise, in order to allow readers to understand the concept of theoretical concepts, but also avoid the boring feeling of reading textbooks. The example I'm going to cite this time is the company. It's not necessarily an IT company, try to be a little bit far away from the programming world, let's assume it's a moving company.

If we think of the company as a process, then the person is the thread. Process must have a main thread, the company in the early days of the start-up may appear one person conquer phenomenon, but, at least one person, the company can operate. Company start-up, business is not too much, often is the boss of a person and several jobs, if only 1, 2 times a day, should still be busy to come over. Long time, with the development of business, the establishment of word-of-mouth, business more and more prosperous, a person must be busy. Suppose there are 5 jobs a day, the boss a person must move a home to move B, moved to dusk estimated also moved to C home, D and E home are still anxiously waiting. The boss of a person to act as a porter, driver, Business Contact, legal representative, cashier and many other roles, the size of the company is not Red, manpower is not enough to restrict the development of the company. So what to do, very simple, to increase the number of people, in the programming word is "again a thread."

We are now using code to describe such a scenario, first of all, we are ready to set up a moving company, so we have to prepare for the future and the client signed the contract:

 Public classcontract{ Public stringID {Get;Private Set; }  Public stringfrom {Get;Set; }  Public stringto {Get;Set; }  Public decimalFee {Get;Set; }  Publiccontract () { This. ID =Guid.NewGuid (). ToString ()}}

Jane is a little simpler, at least it is a contract, now we go to apply for a company, and set up a good start-up team, even if only the owner of a person:

 Public classhousemovingcompany{Private StaticHousemovingcompany _instance =NULL;  Public Statichousemovingcompany Instance {Get{return(_instance = =NULL? _instance =NewHousemovingcompany (): _instance); }    }      PublicList<contract> Contracts {Get;Private Set; }  PublicHousemovingcompany () { This. Contracts =NewList<contract>(); }      Public voidMovehouse () {if( This. Contracts = =NULL|| This. Contracts.count = =0)        {            return; } Contract Contract= Contract = This. contracts[0];  This. Contracts.removeat (0); if(! String.IsNullOrEmpty (contract. From) &&!String.IsNullOrEmpty (contract. To) {Console.WriteLine ("Move the house from {0} to {1}.", contract. From, contract.        To); } thread.sleep ( the); }}

OK, now the company entity has, the boss can start busy:

 static  void  Main (string  [] args) {HouseMovingCompany.Instance.Contracts.Add ( new  Contract {from =  " wudaokou  Span style= "color: #800000;" > ", to = "  linda Road   ", Fee = 500  });  while  (HouseMovingCompany.Instance.Contracts.Count > 0  ) {HouseMovingCompany.Instance.MoveHouse (); }}

We set the move in front for 5 seconds, so let's think of it as 5 hours. Well, a day after a list, but also acceptable, but with the boss business is booming, sometimes a day to pick up 3 of the list, which will work at least 15 hours, but also worry about the company's operations and other issues, indeed busy, and according to this calculation, the boss can not complete a day 5 or more than 5 of the list, Seriously restricts the development of the company:

Static voidMain (string[] args) {HOUSEMOVINGCOMPANY.INSTANCE.CONTRACTS.ADD (NewContract {from ="Wudaokou", to ="LinDa Road", Fee = - }); HOUSEMOVINGCOMPANY.INSTANCE.CONTRACTS.ADD (NewContract {from ="Xidan", to ="wangfujing", Fee = + }); HOUSEMOVINGCOMPANY.INSTANCE.CONTRACTS.ADD (NewContract {from ="Xiangshan", to ="The Forbidden City", Fee =10000 });  while(HouseMovingCompany.Instance.Contracts.Count >0) {HouseMovingCompany.Instance.MoveHouse (); }}

One night, the boss dragged tired body back home, a door fell on the bed, he tried to open the eyes, hard to himself said: "No, I must think of a way, otherwise I will be exhausted!" ”。

In fact, the way is very simple, who know, recruit a few employees, and then buy a few cars, we split up, not only to share the burden of work, but also in the scale of the expansion can be completed more larger list. OK, let's use the multithreading mechanism to implement our ideas now:

 Static voidMain (string[] args) {HOUSEMOVINGCOMPANY.INSTANCE.CONTRACTS.ADD (NewContract {from ="Wudaokou", to ="LinDa Road", Fee = - }); HOUSEMOVINGCOMPANY.INSTANCE.CONTRACTS.ADD (NewContract {from ="Xidan", to ="wangfujing", Fee = + }); HOUSEMOVINGCOMPANY.INSTANCE.CONTRACTS.ADD (NewContract {from ="Xiangshan", to ="The Forbidden City", Fee =10000 }); Thread Thread=NULL;  while(HouseMovingCompany.Instance.Contracts.Count >0) {Thread=NewThread (NewThreadStart (HouseMovingCompany.Instance.MoveHouse)); Thread.     Start (); } }

In this procedure, we split up, let each move task by a small team to complete, and we found that the time to do three is the same as the time to make a list, improve efficiency and expand the size of the company. However, since the introduction of new working mechanisms, we have to make some small adjustments within the company:

 Public voidMovehouse () {if( This. Contracts = =NULL|| This. Contracts.count = =0)    {        return; } Contract Contract=NULL; Lock( This. Contracts) {Contract= This. contracts[0];  This. Contracts.removeat (0); }     if(! String.IsNullOrEmpty (contract. From) &&!String.IsNullOrEmpty (contract. To) {Console.WriteLine ("Move the house from {0} to {1}.", contract. From, contract.    To); } thread.sleep ( the);}

The adjustment is just movehouse some of the implementation details inside this method. The company received the list is kept in the contracts, so when moving to take a list and then according to the information on the list to work. Originally we had only one thread in operation contracts, but also do not feel anything, now there are many threads are in the contracts elements in the access, we have to beware of some accidents. This is the use of multithreading often need to consider the concurrency problem, so we used the lock keyword, when a thread to operate contracts, it first lock up contracts, in fact, is to declare: "Now I operate it, you do not move, and so I finished." "The object that was locked at the end of the lock block is unlocked, and the other thread is now able to manipulate it."

With the multithreading mechanism, you will find that the program can do more in a shorter period of time. This article does not enumerate through all the concepts in the multithreaded mechanism, but has shown you how to use multithreading and when to consider multi-threading, and some other details await you to further explore, for example, you can set the priority of a thread (assuming that it is logically linked to the fee, similar to the ' Expedited ') and so on.

Master the multithreading mechanism and let it make your application more powerful.

About multithreaded Vernacular edition

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.