Java----Multithreading Knowledge point Induction (concept)

Source: Internet
Author: User
Tags instance method thread class

One, the difference between the thread and the 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 of the thread itself is usually only the register data, and a

The stack used when the program executes, so the thread's switchover is less burdensome than the process switch. The purpose of multithreaded programming is to "maximize the use of CPU resources", when a thread processing does not need to occupy the CPU and only

When dealing with resources such as I/O, allow other threads that require CPU resources 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 produce threads ourselves, then the system will generate a thread for us
(The main thread, the main method runs on the main thread), and our program is executed by the thread.


2. Process: Executing program (program is static concept, process is dynamic concept)

3. There are two ways to implement a thread:

The first way is to inherit the thread class and then rewrite the Run method;
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 then start the thread with the Start method.
The Start method first prepares the system resources for the execution of the thread and then calls the Run method. When a
After 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 all thread objects

Shared (because it is a member variable of static).

3) When using the first method to generate a thread object, we need to rewrite the Run method because the thread class's Run method

There is nothing to do 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 will mythread the class's Run method, so that the Run method we write ourselves executes.


Description
public void Run () {
If (target!=null) {
Target.run ();
}}
When a thread object is generated using the inherited thread, target is empty and nothing is executed.

When the second method is used to generate, execute Target.run (), Target is the instance object of Runnable,

That is, to execute the overridden method

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. Typically, when a thread has inherited another class,

The second method should be constructed, that is, the implementation of the Runnable interface.

Four: The life cycle of a thread:


1). Create Status:
The thread is created when a new thread object is created using the new operator.

The thread in the creation 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 calls 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 be running.

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 satisfy

Thread input/output blocking

4) Return to operational status:

A thread that is asleep after the specified time has passed

If a thread waits 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.

You typically set a variable, which is a loop in the Run method, and the loop checks the variable every time.

If the condition is met, the execution continues, otherwise it jumps out of the loop and the thread ends.

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


Five: Multithreading Concurrency:

Multithreading concurrency is a common phenomenon in thread synchronization, in which Java multithreading is used to avoid

Multithreading concurrency solves the problem of multi-threaded shared data synchronization with synchronized keyword


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 a monitor,

When you access an object's synchronized method, it means that the object is locked, and any other thread

Can no longer access the Synchronized method until the previous thread has finished executing the method.

(or throws an exception), the object's lock is freed, and other threads are likely to access

The Synchronized method.

2. If an object has multiple synchronized methods, one time a thread has entered the

A synchronized method, the other thread is inaccessible until the method has finished executing

Any of the synchronized methods of the object.

3. If a synchronized method is static, then when the thread accesses the method, it does not lock the

The object that the Synchronized method resides in, but the class object that corresponds to the object where the Synchronized method resides

Because in Java, no matter how many objects a class has, these objects correspond to a unique class object, so when

When a thread accesses two static,synchronized methods of two objects of the same class respectively, their execution

The order is also sequential, that is, one thread executes the method first, and the other thread executes when it is finished.

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 where only one thread can execute the synchronized method at a time;
The synchronized block is a fine-grained concurrency control that synchronizes the code in the block, in the method, in the synchronized block
Outside of the code can be accessed by multiple threads at the same time.

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 the call, so calls to both methods need to be placed in the Synchronized method
or blocks. 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
The lock of the object is not freed during the process.
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 thread that is woken up will be in the usual manner with the active synchronization on the object.
all other threads compete; for example, a thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks this 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 influence each other on the 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 role of the "synchronized" keyword is that
Ensure that only one thread at a time is allowed to execute a particular block of code, so 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
Synchronizing their actions, the simplest way to implement synchronization in a Java program is to lock. In Java programming, all objects have locks. Threads can use synchronized
Keyword to get the 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 allows Java threads to communicate quickly and easily
and synchronization. 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 the execution process.
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 another thread
Required locks, which are blocked when waiting on each other, can be deadlocked.
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
The thread itself uses the object that other threads do not need to access, nor 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 each thread
A new object in the action to create an object, each thread creates a copy or copy of an object that is not something. This newly created by Threadlocal.set ()
The object's reference is saved to each thread's own map, and each thread has a map that executes Threadlocal.get () when each thread from its own map
So that 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
The shared object itself, or a concurrent access issue.

Java----Multithreading Knowledge point Induction (concept)

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.