"Java" uses synchronized (this) to complete the critical section of a thread

Source: Internet
Author: User
Tags semaphore ticket

In the "Java" thread concurrency, mutual exclusion and synchronization (click Open link) in the operating system through the operation of the original method of semaphore control, complete the thread of mutual exclusion and synchronization, say a digression, in fact, this signal volume algorithm, is the famous Dijkstra created, that is, the data structure, The shortest path algorithm, Dijkstra algorithm and Dijkstra algorithm are the contributors of the computer network. In fact, in Java there is no need to define a semaphore to achieve the critical area, Java for the implementation of the critical area is already encapsulated, and synchronized is the Java keyword.

So, how do you use this keyword? The following is the last "Java" thread concurrency, mutual exclusion and synchronization (click Open link) in the program to improve, without the semaphore, the same to implement the corresponding function inside.


I. BASIC OBJECTIVES

First to review the "Java" thread concurrency, mutual exclusion and synchronization (click Open link) in the program, said that there are four cattle, thread 1, thread 2, thread 3, thread 4, the purpose is to brush the ticket station inside the 20 tickets, and each rob their votes, will not appear a number of cattle rob a ticket situation, Which means one ox corresponds to a ticket.


Also, each run has a different result:


This program was last used to achieve the signal volume, the following use synchronized (this) to complete the critical section of the thread, here is the ticket to the part, there is only one ticket window, each time can only hold one ox to rob tickets, and this time each thread is CPU frequency to brush the ticket, Brush 2000 is not virtual, each completion of the results are different, and a ticket only landed in the hands of an ox,


does not produce the following unordered, disorderly conflicts:


Even brush 20000 votes are not empty:


As the program is robust, you can still run as you change to 200,000 sheets:


Each run results differently due to the different resources allocated by the CPU.


Second, the basic idea:

The so-called use of synchronized (this) to complete the critical section of the thread, is in a implements Runnable process class has the following section of code, forming the so-called Thread critical section:


As for many operating systems that do not know what to write, this is what the critical section says: The code that accesses the critical resource in each process is called the critical section (The Critical section) (The critical resource is a shared resource that only one process is allowed to use at a time). Only one process is allowed to enter the critical section at a time, and no other process is allowed to enter. Whether it is a hardware critical resource or a software critical resource, multiple processes must be mutually exclusive to access it.

In fact, here, the ticket is the critical resource, the critical area is how the ox buy tickets.


Third, the production process

1, first and "Java" thread concurrency, mutual exclusion and synchronization (click to open the link) as in the main function to open a process, wherein the process has four threads:

public class ThreadTest {public static void main (string[] args) throws Exception {GetTicket GetTicket = new GetTicket (); NE W Thread (GetTicket, "Thread 1"). Start (); New Thread (GetTicket, "Thread 2"). Start (); New Thread (GetTicket, "Thread 3"). Start (); new Thread (GetTicket, "Thread 4"). Start ();}}

2. This process class is as follows:

Class GetTicket implements Runnable {//ticket is the number of votes, Isnotread is set to output only once for the output of the statistic private int ticket = 200000;private Boolean isnotread = true;private int count1 = 0;private int count2 = 0;private int count3 = 0;private int count4 = 0;publi c void Run () {while (This.ticket > 0) {//critical section start, so-called critical area is only one thread can access the part synchronized (this) {if (This.ticket > 0) {//Pair ticket For this.ticket--; System.out.println ("Ticket" + (200000-this.ticket) + "by" + Thread.CurrentThread (). GetName () + "buy away, current number of votes remaining:" + this.ticket);// Thread.CurrentThread (). GetName () takes the name of the current thread 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;}} else {//These 4 threads will pass through here anyway, so in order to output only once, you must set a Boolean value//This isnotread is also a semaphore to some extent if (Isnotread) {System.out.println ("^_^ ticket has been sold out , tomorrow morning, each of them scattered! (Kill All Processes) "); System.out.println ("========= statistics ========="); SYSTEM.OUT.PRINTLN ("Thread 1:" + count1 + "Zhang"); SYSTEM.OUT.PRINTLN ("Thread 2:" + Count2 + "Zhang"); System.out.println ("Thread 3:" + Count3 + "Zhang"); System.out.println ("Thread 4:" + count4 + "Zhang"); isnotread = false;} This paragraph is equivalent to Thread.currentThread.stop (), which is recommended by Eclipse in JDK1.7 Thread.yield ();}} Critical section End}}}

Therefore, the whole process is as follows:

Class GetTicket implements Runnable {//ticket is the number of votes, Isnotread is set to output only once for the output of the statistic private int ticket = 200000;private Boolean isnotread = true;private int count1 = 0;private int count2 = 0;private int count3 = 0;private int count4 = 0;publi c void Run () {while (This.ticket > 0) {//critical section start, so-called critical area is only one thread can access the part synchronized (this) {if (This.ticket > 0) {//Pair ticket For this.ticket--; System.out.println ("Ticket" + (200000-this.ticket) + "by" + Thread.CurrentThread (). GetName () + "buy away, current number of votes remaining:" + this.ticket);// Thread.CurrentThread (). GetName () takes the name of the current thread 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;}} else {//These 4 threads will pass through here anyway, so in order to output only once, you must set a Boolean value//This isnotread is also a semaphore to some extent if (Isnotread) {System.out.println ("^_^ ticket has been sold out , tomorrow morning, each of them scattered! (Kill All Processes) "); System.out.println ("========= statistics ========="); SYSTEM.OUT.PRINTLN ("Thread 1:" + count1 + "Zhang"); SYSTEM.OUT.PRINTLN ("Thread 2:" + Count2 + "Zhang"); System.out.println ("Thread 3:" + Count3 + "Zhang"); System.out.println ("Thread 4:" + count4 + "Zhang"); isnotread = false;} This paragraph is equivalent to Thread.currentThread.stop (), which is recommended by Eclipse in JDK1.7 Thread.yield ();}} Critical section End}}}public class ThreadTest {public static void main (string[] args) throws Exception {GetTicket GetTicket = new Gett Icket (); New Thread (GetTicket, "Thread 1"). Start (); New Thread (GetTicket, thread 2). Start (); New Thread (GetTicket, "Thread 3"). Start (); New Thread (GetTicket, "Thread 4"). Start ();}}

Well, since the critical section is how to write, then the producer, consumer issues, readers, the question of the barber, the question of the Philosopher's meal, or the problem? is to show tease, joking, send points! All is a reason, is to come to see you, how to deal with several processes to request the same resource, how do you arrange to avoid the following situation:



"Java" uses synchronized (this) to complete the critical section of a thread

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.