"Java" thread concurrency, mutex and synchronization

Source: Internet
Author: User
Tags semaphore

On the network for thread resolution always smallpox dragon and Phoenix, to you instill a lot of concepts, postgraduate examination, undergraduate operating system, especially, so you even carefully read a lot of articles do not know what to do.

The following do not take the site copy and paste, in the explanation of their Java thread concurrency, mutual exclusion and synchronization before the first to solve the operating system book those who give the book to the person who wrote the nonsense in the end what the meaning.

If the gods only want to see the program, you can skip, anyway, my article is always novice to, do not like to see.


First, the basic concept of threading

In fact, the concept of threading is very simple, one more thread, there is a person to do things.

such as moving things, moving 10 cases of cargo, this is called a process, a person, is called a thread, the 10 box of goods from one side to the other, that is, the so-called completion of a process, of course, compared to the number of people to move 10 boxes of goods from one side to the other end of the efficiency, The so-called multithreading completes a process that is more efficient than a single thread to complete a process. Which needs a lot of space like some books, some teachers use a lot of classes to explain what is threading and process?

Today's multi-threaded operating system, such as windows, its advantage is that many people do one thing at the same time, so fast, improve efficiency.

Of course, so many people move things also caused some problems, such as when moving things, there is a time, two people at the same times to carry out their own goods, and start moving the next cargo, then, when the two person saw the same goods, when they want to move the goods when the negotiation. Of course, this who moved first who moved without any relationship, but you two people do not move a cargo at the same time, that is, I this manager, must ensure that all involved in the handling of the person, a cargo for a person, so that the efficiency of transport to maximize, the rules of transport to establish the people who move things will not quarrel. This is called a thread mutex problem. If this is the case, I have to set up a buffer to carry things. You have to queue before you move things, you take turns to get things, rules, so you don't quarrel.

If someone in front of you do not have a good thing, the people behind to carry things, no matter how fast you hands and feet, you have to wait for me! The man who took the thing set the flag before he took the thing, and took the flag after taking the thing. Let's have a good look at flag before anyone moves anything. This is called "the process of access to critical resources of the code called Critical section," The critical resource is something, you have to take something is access to critical resources, the critical section is the queue waiting to take things.

Finally there is a concept of thread synchronization, so-called synchronization, that is, if after the process of moving things, there is a need to transport things, you have to wait for everything to move, he can start to carry things, moving things is a process, the transport of things is a process, then the two processes form a synchronization. The process is the thread, the essence is the same, but the process is a large number of threads of the collection, that is, the process is a big thing, the thread is a small thing. The so-called big things are different for different people, for example, for some people, back to the dorm playing game is a big thing, process, open the computer is trivial, thread, and for some people, to get a famous university admission notice is a major event, thread, every day good study is trivial, thread. So the process is also relative to the thread.


Implementation of thread concurrency, mutual exclusion and synchronization in Java

Java is actually only more complex than the MFC, C + + simple, the use of the class name, method is clearer, but not much, because it contains too much, but it is also its benefits, like assembly language, the more difficult you write, the more difficult things to learn, but the most useful things, It can control a lot of things, Java is can open multi-threaded, some language estimates do not let this engage.

1. Basic objectives

Suppose we want to write a program like this: There are four scalpers, the name is thread 1, thread 2, thread 3, thread 4, their task is the robbed ticket station inside the 20 tickets, the conductor's sell a ticket needs 1s, thread 1 of the rate is every 1s buy 1 tickets, thread 2 is 2s/ticket, thread 3s/ticket, Thread 4 is the 0.5s/ticket, and then the main thread main command they start to rob the ticket, waiting for all tickets of the ticket station is sold to count the situation of each ox's ticket.


The whole program ran out of the results as shown above, of course, the processing rate is not so fast, I do gif, the time to wait was cut off, not everyone to see so slow, the file is not so big.

Here is an example of multithreading concurrency, if 1 threads no longer have to brush the ticket of course there is no order problem, will not appear in a certain time multiple threads to a ticket request, there is no concept of buffer. And then the last to do statistics of the main thread also do not have to wait, must order the structure of the program, statements and statements before the default is a synchronous relationship, here to consider the end is waiting for the process to complete before starting to do their own things.

If we change the rate of each ox, we get a different result:


Through the comparison of the two programs, we can also find that the fast cattle, no matter how the program run, the last to get a lot of votes, which conforms to the natural law.

If a yellow ox hands and feet too slow, it will appear long-term in the buffer zone situation, the last to get fewer votes, or even no, there is the so-called "starve" concept, that is, long-term access to resources.

In fact, this society is also, if you are too useless, inefficient work, hands and feet slow, you do not want to get the resources of society. If you want to be successful, get a lot of social resources, then from now on, please improve your work efficiency, and try to quit procrastination Oh!

2, the production process

(1) Main function

This program does not need to introduce any Java package in the program header, the JDK comes with

Note that you create this Java program, please do not name it as thread, so you are dead, because thread is a keyword in a java program

public class ThreadTest {public static void main (string[] args) throws Exception {MyThread my = new MyThread (); New Thread ( My, "Thread 1"). Start (); New Thread (My, thread 2). Start (); New Thread (My, thread 3). Start (); New Thread (My, thread 4). Start (); My.semaphoretomain = = 0) {System.out.println (Thread.CurrentThread (). GetName () + "to buffer"); try {thread.currentthread (). Sleep (4000);} catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println ("^_^ ticket has been sold out, tomorrow morning, all the respective scattered!" (Kill All Processes) "); System.out.println ("========= statistics ========="); SYSTEM.OUT.PRINTLN ("Thread 1:" + my.count1 + "Zhang"); SYSTEM.OUT.PRINTLN ("Thread 2:" + My.count2 + "Zhang"); System.out.println ("Thread 3:" + My.count3 + "Zhang"); System.out.println ("Thread 4:" + my.count4 + "Zhang");}}
The thread needs to throw an exception,

How to open the thread, as shown above, Mythread is a process I'm going to write for a while, creating a new Mythread process whose name is my, while thread 1, thread 2 、...... It is clearly the thread of this my process.

As for the following code:

while (My.semaphoretomain = = 0) {System.out.println (Thread.CurrentThread (). GetName () + "to buffer"); try { Thread.CurrentThread (). Sleep (4000);} catch (Interruptedexception e) {e.printstacktrace ();}}

is the so-called buffer, start by throwing the main function into the buffer to sleep,

Until my this process and you interact with the signal volume is not 0, you just give me out, of course, you do not often ask me whether the semaphore is 0, you ask me to sleep 4s, that is, you 4s just to ask me once, or I am bored to death, that is, I do not like my program appears as the "broadcast Storm".

Until main leaves this buffer, it can execute the following statistic code and output.

(2) Mythread process

Overwrite Runnable interface, actually explain oneself is a multithreaded operation process, group P ^_^ Hehe class MyThread implements Runnable {//Suppose there are 20 tickets, In fact, the following 4 threads each action is to make this ticket value from 0private int ticket = 20;//This is the self-reducing mutex semaphore private int semaphore = 0;//These things are to be accessed by the main function, so it is public, The above two values can only be used in this process, so is Private//countx is process X's votes statistics, semaphoretomain with the main function of the semaphore public int count1 = 0;public int count2 = 0;public int count3 = 0;public int count4 = 0;public int semaphoretomain = The execution of the 0;//process, write public void Run () in the following run () method () {//Pawn ticket not 0 start to play happily while (This.ticket > 0) {//thread.currentthread (). GetName () This method can take the thread name switch (Thread.CurrentThread () that is now making the process. GetName ()) {///if it is thread 1, enter this thread first give me sleep 1s, and so on, actually control the speed of each thread//If you do not let the line enters upgradeable sleep for a while, they will be at the CPU frequency, every 3.19GHZ of the reciprocal of an action rate in the run//part of the Divine machine estimated faster , this experiment does not produce the result case "Thread 1": try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} Break;case "Thread 2": try {thread.sleep (+);} catch (Interruptedexception e) {e.printstacktrace ();} Break;case "Thread 3": try {thread.sleep;} catch (Interruptedexception e) {e.printstacktrace ();} Break;case "Thread 4": try {thread.sleep (500);} catch (Interruptedexception e) {e.printstacktrace ();} break;} This is also the buffer, once there is a process operation ticket, it must change the semaphore to 1, let the other process into the buffer//when it is finished, and then change the semaphore back to 0, all in the buffer process to compete for ticket eligibility//will not be a ticket for simultaneous operation, a ticket to rob Rotten while ( Semaphore > 0) {System.out.println (Thread.CurrentThread (). GetName () + "to buffer"); try {//You group of thread X, also is often to me check whether this semaphore is 0, I don't want to get bored. Thread.CurrentThread (). Sleep (1000);} catch (Interruptedexception e) {e.printstacktrace ();}} if (This.ticket > 0) {semaphore++;try {thread.sleep (+);} catch (Interruptedexception e) {e.printstacktrace ();} this.ticket--; System.out.println ("Ticket" + (20-this.ticket) + "by" + Thread.CurrentThread (). GetName () + "buy away, current number of votes remaining:" + this.ticket); switch ( Thread.CurrentThread (). GetName ()) {case "Thread 1": This.count1++;break;case "Thread 2": This.count2++;break;case "Thread 3": This.count3++;break;case "Thread 4": this.count4++;break;} semaphore--;} else {///all tickets are bought, then notify the main function main, you start to leave the buffer, take statistics semaphoretomain++;//eclipse this stop () method will be underlined warning, after all, the Stop () method may cause a deadlock, The mutex and the sync lock are already encapsulated in Java//eclipse recommended that this program implement Thread.CurrentThread () with a mutex and a synchronous lock. Stop ();}}}
The comments above are already clearer,

Please also note that this code of the ticket operation:

If now is the postgraduate examination or undergraduate operating system final exam, change the volume of the teacher must see you before and after the operation of the signal volume processing. semaphore++;semaphore--; This pair, in the operation of the thread, must be threaded corresponding, as assembly language and interface technology, if there is a function, process operation, remember to stack a pair to save the scene!

"Java" thread concurrency, mutex and synchronization

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.