Multi-threaded explanation

Source: Internet
Author: User

This article is from: Cao Shenhuan blog column. Reprint Please specify source:http://blog.csdn.net/csh624366188

Multithreading is a feature of Java applications, and mastering Java multithreading is also a prerequisite for Java programmers. Multithreading refers to the ability to run multiple identical threads concurrently in a single program to perform different tasks. Threads are sequential control flows within a program and can only use resources and environments that are assigned to the order. I remember when I first started to learn the process is always confused with the processes, always to the two of these nouns.

The first of these two nouns is the beginning of this blog:

The difference between a thread and a process

The internal data and state of multiple processes are completely independent, and multithreading is a shared piece of memory space and a set of system resources that may interact with each other. • The data for the thread itself usually has only the register data and a stack used by the program when it executes, so the thread switching is less burdensome than the process switching.

The purpose of multithreaded programming is to "make the most of CPU resources", when the processing of a thread does not need to consume CPU and only to deal with resources such as I/O, so that other threads that need CPU resources have the opportunity to gain CPU resources. Fundamentally, this is the ultimate goal of multithreaded programming.

Second, learn the basics of Java in multi-threading

1.Java If we do not generate a thread ourselves, then the system will give us a thread (the main thread, the main method is running on the main thread), our program is executed by the thread.

2. Process: Executing procedure (the concept of a procedure is static, the process is a dynamic concept).

3. There are two ways to implement a thread, the first is to inherit the thread class, then rewrite the Run method, and the second is to implement the Runnable interface and then implement its Run method.

4. Put the code that we want the thread to execute into the Run method and start the thread with the Start method, whichfirst prepares the system resources for the execution of the thread and then calls the Run method. when a class inherits the thread class, the class is called a thread class.

5. A process must contain at least one thread.

6. For a single-core CPU, only one thread can execute (micro-serial) at a time, and from a macro point of view, multiple threads are executing simultaneously (macro parallel).

7. For a dual-core or dual-core CPU, you can really do micro-parallelism.

Three, thread source code research:

1) The thread class also implements the Runnable interface, thus implementing the Run method in the Runnable interface;

2) When a thread object is generated, if no name is set for it, then the name of the thread object will be used as follows: Thread-number, the number will be automatically incremented and shared by all thread objects (because it is a static member variable).

3) When using the first method to generate the thread object, we need to rewrite the Run method because the thread class's Run method does not do anything at this time.

4) When using the second method to generate the thread object, we need to implement the Run method of the Runnable interface, and then use the new thread (new MyThread ()) (if MyThread has implemented the Runnable interface) to generate the thread object. The Run method or tune of the thread object at this point would mythread the class's Run method, so that the Run method we wrote was executed.

Description

public void Run () {

If (target!=null) {

Target.run ();

}}

When the thread object is generated using the inherited thread, target is empty and nothing is executed when the second method is used to execute the Target.run (), the target is the instance object of Runnable, which is the method to execute the override

Summary: The difference between two types of generated thread objects:

1. Two methods are required to execute the thread's Start method to assign the required system resources to the thread, schedule the thread to run, and execute the thread's Run method.

2. In specific applications, the method used to construct the thread body depends on the situation. In general, when a thread has inherited another class, it should be constructed in the second way, that is, implementing the Runnable interface.

Four: The life cycle of a thread:

As can be seen, a thread from birth to death is divided into five stages:

1). Create status

• When a new thread object is created with the newly operator, the thread is in the created state.

• The thread in the created state is just an empty thread object and the system does not allocate resources for it

2). Operational status

• The start () method of the execution thread assigns the required system resources to the thread, schedules it to run, and invokes the thread body-run () method, which causes the thread to be in a running (Runnable) state.

• This state is not in the running state (Running) because the thread may not actually run.

3). Non-operational status

. When the following event occurs, the running thread is moved to a non-operational state.

Called The Sleep () method;

• The thread calls the wait method to wait for a specific condition to be satisfied

• Thread input/output blocking

4) Return to operational status:

• A thread in sleep after a specified time has elapsed

• If the thread is waiting for a condition, the other object must notify the waiting thread condition through the Notify () or Notifyall () method

• Wait for input/output to complete if thread is blocked by input/output

5). Extinction status

When the thread's Run method finishes executing, the thread dies naturally.

Attention:

1. How to stop a thread: You cannot use the thread class's Stop method to terminate the execution of a thread. In general, to set a variable, in the Run method is a loop, each time the loop checks the variable, if the condition is satisfied to continue to execute, or jump out of the loop, the thread ends.

2. You cannot rely on thread precedence to determine the order in which threads are executed.

V: Multithreading concurrency

Multithreading concurrency is a common phenomenon in thread synchronization, and Java multithreading provides the synchronized keyword to avoid multi-threaded concurrency to solve multi-threaded shared data synchronization problems.

Synchronized keyword: When the synchronized keyword modifies a method, the method is called a synchronous method.

Each object in the 1.Java has a lock (lock) or monitor, and when the synchronized method of an object is accessed, it means that the object is locked, and no other thread can access the Synchronized method again. Until the previous thread executes the method (or throws an exception), the object's lock is freed and other threads are likely to access the Synchronized method again.

2. If an object has more than one synchronized method and a thread has entered a synchronized method at some point, the other thread is unable to access any of the synchronized methods of the object until the method has finished executing.

3. If a synchronized method is static, then when the thread accesses the method, it locks not the object that the Synchronized method resides in, but the class object that corresponds to the object that the synchronized method is in. Because no matter how many objects a class has in Java, these objects correspond to a unique class object, so when a thread accesses two static,synchronized methods of two objects of the same class individually, their order of execution is also sequential, that is, a thread first executes the method, After execution, another thread starts executing.

4. Synchronized block, notation:

Synchronized (object)

{

}

Indicates that the thread will lock the object when executing.

The 5.synchronized method is a coarse-grained concurrency control in which only one thread can execute the synchronized method at a time, and the synchronized block is a fine-grained concurrency control that synchronizes code in the block, within the method, Code outside the synchronized block can be accessed concurrently by multiple threads.

Thread state diagram for synchronization:

Six: Wait and notify

Both 1.wait and notify methods are defined in the object class and are final, so they are inherited by all Java classes and cannot be overridden. These two methods require that the thread should have acquired the lock on the object at the time of invocation, so calls to both methods need to be placed in the Synchronized method or block. When a thread executes the wait method, it releases the lock on the object.

2. Another method that causes thread pauses is the sleep method of the thread class, which causes the thread to sleep for a specified number of milliseconds, but the thread does not release the lock on the object during sleep.

3.notify (): Wakes up a single thread waiting on this object monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods.

Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object.

This method should be called only by threads that are the owner of this object monitor. A thread can be the owner of this object monitor by one of the following three methods:

o by executing the synchronous instance method of this object.

o The body of the synchronized statement that is synchronized by executing on this object.

O for objects of class type, you can do this by executing a synchronous static method of the class.

Only one thread can have a monitor for an object at a time.

about member variables and local variables : If a variable is a member variable, then when multiple threads manipulate member variables of the same object, they affect each other on that member variable (that is, a thread changes the member variable to affect another thread). If a variable is a local variable, then each thread will have a copy of that local variable, and one thread's change to that local variable will not affect other threads.

Seven: The deadlock problem:

Definition: Thread 1 locks the monitor of object A, waits for the monitor of object B, thread 2 locks the monitor of object B and waits for the monitor of object A, causing a deadlock.

The root cause of deadlocks is the inappropriate use of "synchronized" keywords to manage thread access to specific objects. The purpose of the "synchronized" keyword is to ensure that only one thread at a time is allowed to execute a particular block of code, so that the thread being allowed to execute must first have exclusive access to the variable or object. When a thread accesses an object, the thread locks the object

Each object in Java has a lock corresponding to it. However, Java does not provide separate lock and unlock operations. The following author analyzes the two processes of deadlock "locked" and "locked".

(1) lock
Many threads must consider sharing data or coordinating execution state with other threads in execution, requiring a synchronization mechanism. So most applications require threads to communicate with each other to synchronize their actions, and the simplest way to implement synchronization in a Java program is to lock it. In Java programming, all objects have locks. Threads can use the Synchronized keyword to obtain a lock. At any one time for instances of a given class, methods or synchronized code blocks can only be executed by one thread. This is because the code asks for a lock on the object before it executes.

To prevent access to shared resources at the same time, the thread can lock and unlock the resource before and after the resource is used. Locking shared variables makes Java threads fast and easy to communicate and synchronize. A thread Chengjo a lock on an object so that no other thread can access the object. Even in a preemptive model, other threads are not able to access this object until the locked thread is awakened, the work is completed, and the lock is unlocked. Threads that attempt to access a locked object usually go to sleep until the locked thread locks. Once the lock is opened, these sleep processes are awakened and moved to the ready queue.

(2) Lock dead
If there are several concurrent threads competing for resources in the program, it is important to ensure that the balance is guaranteed. System equalization means that each thread has full access to limited resources during execution, and that there are no starved and deadlocked threads in the system. When multiple concurrent threads attempt to occupy two locks at the same time, there is a case of a lock conflict. If one thread occupies a required lock on another thread, it is possible to deadlock when waiting on each other.

In writing multithreaded code, I think deadlock is one of the most difficult problems to deal with. Because deadlocks can occur in the most unexpected places, it is time-consuming and laborious to find and fix them. For example, a common example is the following procedure. Print?

1 public int sumarrays (int[] A1, int[] A2) {

2 int value = 0;

3 int size = A1.length;

4 if (size = = A2.length) {

5 synchronized (A1) {//1

6 synchronized (A2) {//2

7 for (int i=0; i<size; i++)

8 value + = A1[i] + a2[i];

9}

10}

one} return value;

12}

This code locks both array objects before accessing two array objects in a summation operation. It is short in form and suitable for the tasks to be performed; Unfortunately, it has a potential problem. The problem is that it buries the seeds of the deadlock.

Threadlocal Class (This class I did not use, occupy the time do not understand)

First, ThreadLocal is not used to solve multi-threaded access problems with shared objects, and in general, objects in the thread through Threadlocal.set () are objects that the thread itself uses, and other threads do not need access or access. Different objects are accessed in each thread.

In addition, it is said that threadlocal allows each thread to maintain its own independent object, not by Threadlocal.set (), but by creating an object through the operation of the new object in each thread, creating a copy or copy of each thread that is not an object. The reference to this newly created object is saved to a map of each thread by Threadlocal.set (), each thread has a map that executes Threadlocal.get (), and each thread pulls the object from its own map and So the objects in their own thread are taken out, and the threadlocal instance is used as the key to the map.

If Threadlocal.set () goes in the same object that multiple threads share, then the Threadlocal.get () of multiple threads gets the shared object itself, or there is a concurrent access problem.

Multi-threaded explanation

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.