What is the role of the JAVA thread!__java

Source: Internet
Author: User
in the Java thread to exactly what effect!

This is a very classic on the javaeye thread of the post, written very easy to understand, suitable for any reading computer students.


Thread synchronization We can run various computer software programs on the computer. Each running program may include multiple threads that run independently. Threads (thread) is a stand-alone program that has its own dedicated run stack. Threads may share some resources with other threads, such as memory, files, databases, and so on.


Conflicts can occur when multiple threads are reading and writing the same shared resource at the same time. At this time, we need to introduce the thread "sync" mechanism, that is, the threads should have a arrival, not a swarm of rush into the crowd.


The word sync is translated from English synchronize (making simultaneous occurrences). I don't understand why we should use this very misleading word. Since we all use it, we'll have to do it.


The true meaning and literal meaning of thread synchronization are the opposite. The true meaning of thread synchronization is actually "queuing": Queues between threads, one for the shared resource, not for the same operation.


So the 1th thing to keep in mind about thread synchronization is that thread synchronization is the thread queue. Synchronization is queuing. Thread synchronization is designed to prevent the thread from "synchronizing" execution. This is really a boring tongue twister.


The 2nd word about thread synchronization that needs to be firmly remembered is "sharing". Only read and write access to shared resources requires synchronization. If it is not a shared resource, there is no need for synchronization at all.


The 3rd thing to keep in mind about thread synchronization is that only "variables" require synchronous access. If the shared resource is fixed, it is equivalent to "constant", and the thread does not need to synchronize to read constants at the same time. At least one thread modifies a shared resource, in which case synchronization between threads is required.


As for thread synchronization, the 4th that needs to be kept firmly in mind is that the code that multiple threads access to a shared resource may be the same code, or it may be different code, whether or not the same code is executed, as long as the Threads ' code accesses the same mutable shared resource, the threads need to synchronize.

To deepen your understanding, let me give you a few examples

There are two buyers, their work is the same, are followed by the following steps:

(1) Go to the market and find and purchase potential samples.

(2) Return to the company and write a report.

These two people have the same job, they need to buy samples, they may buy the same kind of samples, but they will never buy the same sample, they do not have any shared resources. So, they can do their own work, do not interfere with each other. The two buyers are equivalent to two threads, and two buyers follow the same work steps, equivalent to two threads executing the same piece of code.


Next, add a work step for the two buyers. The buyer needs to arrange its own work plan according to the information published in the company's "bulletin Board". The two buyers are likely to walk to the front of the bulletin board at the same time and watch the information on the bulletin boards. This is not a problem at all. Since the bulletin board is read-only, neither buyer will be able to modify the information on the bulletin board to add a role. An office executive this time, also went to the bulletin board, ready to change the information on the bulletin board.


If the administrator arrives at the bulletin board first, and is revising the bulletin board's contents. Two buyers this time, happened to be there. The two buyers will have to wait for the administrative staff to complete the changes before they can view the modified information.


If the executives arrive, two buyers are already watching the bulletin board. Then the executives will have to wait for two buyers to record the current information before they can write new information.


In both cases, access to the bulletin board by the administrative staff and the buyer needs to be synchronized. Because one of the threads (administrative staff) has modified the shared resource (bulletin board). And we can see that the executive's workflow and the buyer's workflow (executing code) are completely different, but they need to sync because they have access to the same variable shared resource (bulletin board).


Sync Lock

Before we talk about why we want to synchronize threads, let's see how we can synchronize threads.

Thread synchronization of the basic implementation of the idea is relatively easy to understand. We can add a lock to the shared resource, and this lock has only one key. Which thread acquires the key, has the right to access the shared resource.


Life, we may also encounter such an example. Some of the supermarket's outside provide some automatic storage boxes. Each storage box has a lock, a key. People can use lockers with keys, put things in lockers, lock lockers, and take the keys away. In this way, the bin is locked and no one else can access the locker. (Of course, the real locker key can be taken away and copied, so don't put valuables in the supermarket's storage box.) So many supermarkets have adopted electronic password lock. )


Thread sync lock this model looks intuitive. However, there is still a serious problem unresolved, where the sync lock should be added. Of course it's added to the shared resources. Fast-responding readers will be the first to answer.


Yes, if possible, we will of course try to add the sync lock to the shared resource. Some of the more perfect shared resources, such as file systems, database systems, and so on, themselves provide a relatively perfect synchronization lock mechanism. We do not need to lock these resources separately, and these resources have their own locks.


However, in most cases, the shared resources that we access in our code are relatively simple shared objects. There is no place in these objects for us to lock.


Readers may suggest: Why not add a new area within each object, specifically to lock it up. This design is certainly feasible in theory. The problem is that thread synchronization is not very common. If because of this small probability event, all objects inside all open a lock space, will bring great space waste. Outweigh


So, the modern programming language design idea all is to add the synchronous lock to the code section. Specifically, the sync lock is added to "access the code snippet for a shared resource." It's important to remember that the sync lock is added to the code snippet.


The synchronization lock is added to the code snippet, which solves the problem of space waste. But it increases the complexity of the model and increases the difficulty of our understanding.


Now let's analyze the thread synchronization model for "Sync Lock Plus on code snippet".

First, we have solved the problem of where to add the sync lock. We have determined that the sync lock is not added to the shared resource, but is added to the code snippet that accesses the shared resource.


Second, the question we have to solve is what kind of lock should we add to the code snippet. This issue is the focus of the focus. This is a particular issue we should pay attention to: access to the same shared resources of different code snippets, should be added to the same synchronization lock, if the addition of a different synchronization lock, then simply can not play the role of synchronization, there is no meaning.


This means that the synchronization lock itself must also be a shared object between multiple threads.

Synchronized keywords in the Java language

To deepen your understanding, give a few examples of code snippet synchronization.

Synchronous lock models for different languages are the same. It's just a different way of expressing things. Here we take the current most popular Java language for example. In the Java language, use the Synchronized keyword to lock the code segment. The whole grammatical form is expressed as

Synchronized (Sync Lock) {

Access to shared resources, code snippets that need to be synchronized

}

In particular, it is important to note that the sync lock itself must be a shared object.

... F1 () {

Object lock1 = new Object (); Create a sync lock

Synchronized (LOCK1) {

Code Snippet A

Access shared resources Resource1

Need to sync

}

}


The above code doesn't make any sense. Because the sync lock is generated inside the function body. Each thread invokes this code and a new synchronization lock is generated. So there are different sync locks used between multiple threads. The goal of synchronization is not achieved at all.


Synchronization code must be written in the form of the following to make sense.

public static final Object Lock1 = new Object ();

... F1 () {

Synchronized (LOCK1) {//LOCK1 is a public sync lock

Code Snippet A

Access shared resources Resource1

Need to sync

}

You don't have to declare a sync lock as static or public, but you have to make sure that you use the same sync lock between the associated synchronization code.


When you talk about this, you're going to wonder what this sync lock is. Why do you declare an object object casually, you can be a synchronous lock.


In Java, the concept of synchronous locks is the case. Any object reference can be used as a synchronous lock. We can interpret object reference as the memory address of an object in a memory allocation system. Therefore, to ensure that synchronized code snippets are using the same synchronization lock, we need to ensure that the Synchronized keyword for these sync code snippets uses the same object Reference, the same memory address. This is why I used the final keyword when I declared lock1 in the previous code, which is to ensure that the Lock1 object reference remain unchanged throughout the system.


Some inquisitive readers may want to continue to learn more about the actual operating mechanism of the synchronzied (synchronous lock). In the Java Virtual Machine specification (you can search with keywords like "JVM Spec" in Google), there is a detailed explanation of the synchronized keyword. Synchronized will be compiled into monitor enter, ... monitor exit and so on. Monitor is the actual sync lock. Each object reference is conceptually corresponding to a monitor.


These implementation details are not the key to understanding the synchronization lock model. We continue to look at a few examples to deepen our understanding of the synchronous lock model.


public static final Object Lock1 = new Object ();

... F1 () {

Synchronized (LOCK1) {//LOCK1 is a public sync lock

Code Snippet A

Access shared resources Resource1

Need to sync

}

}

... f2 () {

Synchronized (LOCK1) {//LOCK1 is a public sync lock

Code Snippet B

Access shared resources Resource1

Need to sync

}

}


In the code above, code snippet A and code segment B are synchronized. Because they are using the same sync lock lock1.

If there are 10 threads executing code snippet A at the same time and 20 threads executing code snippet b simultaneously, then all 30 threads are synchronized.


These 30 threads are competing for a synchronous lock lock1. At the same time, only one thread can get lock1 ownership, and only one thread could execute code snippet A or code snippet B. Other competing failed threads can only be paused to enter the ready (Ready) queue for the synchronization lock. Several thread queues are hung below each synchronization lock, including Ready (Ready) queues, waiting queues, and so on. For example, a lock1-ready queue can be called a lock1-ready queue. There may be multiple threads running in each queue. Note that the thread that failed the competing sync lock entered the Ready (Ready) queue for the synchronization lock

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.