Black Horse Programmer _ Multithreading Summary

Source: Internet
Author: User


/**
Multithreading Overview: What is multithreading?
First, what is a process?
A process is the basic unit of system-allocated resources for Windows systems.
A process is a run of a program.
At least one thread exists in a process because the thread is the actual running unit.
Thread: Refers to the control unit in the program, an execution path.
A program can have multiple threads executing concurrently, and each thread is a control unit. A program can have multiple execution lines,
Each line of execution represents a thread.
Thread creation is done by the underlying system, and for threads in Java, the JVM is created by invoking the functionality of the underlying Windows operating system.

Note that the embodiment of a thread on the program and in memory is an object, a thread object. Use a thread class or its subclasses to create
Many different threading objects, that is, a lot of different threads.

Thread creation: There are two ways to create threads:
1. Overwrite the Run method by inheriting the thread class.
2, through the implementation of the Runnable interface, overwrite the Run method.

A thread is a kind of thing that refers to a control unit of a program. There is a description of this class in Java, called the Thread class, and the Run method in that class is
public void Run () {}; The method of doing nothing inside this empty argument is for the subclass of the thread to overwrite it and store it in run
The code to be executed by the thread.
Some methods of the thread class:
public void run ();
Public String getName ();//Returns the name of the thread.
public string SetName (string name);//sets the name of the thread.
public static thread CurrentThread ();//Returns a reference to the currently executing thread object.
public static void sleep (long millis,int Nanos);//causes the thread that executes the method to enter a blocking state and start hibernation.
The first method of creation:
1, by inheriting the thread class.
2. Overwrite the Run method.
3. Store the code that the thread needs to run into the run () method
4. Creating Subclass Objects
5. Call the Start () method of the subclass object, open the thread, and call the Run method.

The second method of creation:
1, by implementing the Runnable interface, define the class.
2. Overwrite the Run method.
3. Store the code that needs to run the thread into the run () method
4. Create the object of the custom class.
5. Create an object of the thread class and pass the object of the custom class as an argument to the parameter constructor of the thread class. Creates a thread class with a
Object.
6. Call the start () method of the Thread class object, open the thread, and invoke the Run method of the custom class object.

The difference between the two ways:
Difference:
The second way, the class implementing the Runnable interface is not a thread class, creating a subclass object for that interface, not creating a thread object.
The second way is to create the thread object by creating an object of the thread class and specifying which object the Run method is running on.

Pros and Cons: The first way, because Java single inheritance, so that the thread subclass can not inherit other classes, can not be one of the other classes. There is a certain
Limitations. The second way, through the implementation of the Runnable interface, the way to avoid the inheritance of thread, so is to avoid the limitations of single inheritance.
The second way to use it as much as possible in real-world development is to extend the functionality defined by the Runnable interface to the interface subclasses.
Any object of a class that implements the Runnable interface can be handed to the thread class object to run its specific content.

The running state of the thread:
There are 5 running states for a thread: A life-like declaration cycle.
The new state, ready state, running state, blocking state, and death state are respectively. Specific as follows:

1. NEW: Creates a thread with the new statement, which is in the new state, which, like other Java objects, is allocated memory only in the heap.
When a thread is in the new state, it is simply an empty thread object and the system does not allocate resources for it.
For example: thread t = new Thread (new Runner ());
2, Ready (runnable): After the program calls the startup method through the Thread object start (), the system will assign the thread to the other than the processor CPU that it needs to run
All system resources. At this point, it is in a state that is ready to run, and at any subsequent point in time, it will enter the running state (running) as soon as it gets the processor.
For example: T.start ();
3. Run (running): The thread in this state consumes the CPU and executes the program code. In a concurrency environment, if the computer has only one CPU, then any moment
Only one of the threads is in this state. If you have multiple CPUs (that is, multicore) in your computer, you can allow several threads to consume different CPUs at the same time so that they are
In the running state, only threads in the Ready state (runnable) have the opportunity to go to the running state. Other thread states cannot be switched directly to the running state,
You must enter the ready state before you can.
4, blocking (blocked): Blocking state refers to the thread for some reason to abandon the CPU, temporarily stop running. When a thread is in a blocked state, the Java Virtual machine does not give
The thread allocates the CPU until the thread re-enters the ready state, and it has the opportunity to go to the running state.
The blocking state can be divided into the following 3:
@1, blocking state in the object's wait pool (blocked in object ' s wait-pool): When the thread is running, if
Executes the wait () method for an object, and the Java Virtual machine puts the thread into the waiting pool for that object.
@2, blocking state in the object's lock pool (blocked in object ' lock Pool): When the thread is in the running state,
When attempting to obtain a synchronization lock on an object, if the object's synchronization lock is already occupied by another thread, the JVM will place the thread in this
The lock pool of the object.
@3, other blocking states (otherwise blocked): The current thread executes the sleep () method, or calls the join () method of another thread,
Or an I/O request is made, this state is entered. When a thread executes the System.out.println () or System.in.read () method,
An I/O request is issued that the thread discards the CPU and goes into a blocking state until the I/O process is complete before the thread resumes execution.
5. Death (dead): When the thread exits the run () method, it enters the death state, which ends the life cycle. It is possible for a thread to execute the run () method properly and
Exit, or you may have encountered an exception and exited. No matter whether a thread ends normally or ends abnormally, it does not affect other threads.

Switching between thread states, the new state can only be ready, ready to run, run can be ready, run can be blocked, blocking can go to
Ready, new, ready, running, blocking can all go to death.

Multithreading security issues: When multiple threads execute the same piece of code and the operation shares the data, a thread-safety issue occurs.

Prerequisites for thread safety issues:
1, at least two or more than two threads exist.
2, at least two or more than two code operations to share resources.

WORKAROUND: Let the thread synchronize.
What's the thread sync? What is thread async?
Threads are random or asynchronous, that is, each thread advances at its own, unpredictable speed. That is, each thread performs its own
, they are irrelevant to each other.
Synchronization refers to the need for mutually exclusive use of a shared resource, or the need for co-operation to create a mutually restrictive relationship. That is, the thread's push execution.
You need to consider the execution of other threads.
The problem with thread safety is to use synchronous code blocks or synchronous functions. The keyword is synchronized.

Synchronizing code blocks:
Synchronized (object)
{
Code blocks that need to be synchronized
}
Synchronization functions:
Synchronized return value type function name ()
{
function body, the code that needs to be synchronized.
}
A synchronized part can only have one thread running at a time, and the synchronized part has a lock, whether it is a synchronous code or a synchronous function, and the lock is an object.
For a synchronous block of code refers to an object in a synchronize (object). For a synchronous function, if it is a non-static synchronization function, it is called by the
The object of the non-static synchronization function, which is this, or, in the case of a static synchronous code block, the class object of the class to which the static synchronization function belongs, that is, the class's
A bytecode file object, the class name. class, which is the name of the object, and the type of the object is the class type.
The entry rule of the synchronization section is that only the thread that gets the lock can go into the synchronization section, and after the synchronization part is executed, the lock is released, without getting the
The thread of the lock cannot enter the synchronization section, only waiting outside because of a lack of resources, discarding the CPU, and entering the blocking state.

Synchronous:
Benefit: Resolves a thread safety issue
Disadvantage: Because each time enters the synchronization part, needs to carry on the lock judgment to the synchronization part, reduces the program efficiency. But sometimes this sacrifice is necessary.

Deadlock: A deadlock is a deadlock that is caused by the lock that is required by multiple threads to occupy the other, and the lock that is requested by the other party.
Cause of deadlock: nested synchronization in synchronization.
Example 1:
Synchronized (Locka)
{
Synchronzied (LOCKB)
}
Synchronized (LOCKB)
{
Synchronized (Locka)
}
Example 2:
sychronized void Show ()
{
Method ();
}
sychronized void Method ()
{
Show ();
}
The lazy type in singleton mode, that is, lazy loading, when there is multi-threaded access, there will be a thread security problem. The workaround is to add synchronous code blocks or synchronous functions.
However, after joining the synchronization, the efficiency of the program is reduced, as each thread enters the synchronization section and the synchronization lock is determined. The optimized solution is to use the
Double judgment, to improve the efficiency of the program.
*/

Class Demo extends Thread{demo (String name) {super (name);} public void Run () {for (int x=0; x<60; x + +) {System.out.println (Thread.CurrentThread (). GetName () + "---run----" +x);}} Class  threaddemo{public static void Main (string[] args) {Demo d = new Demo ("Demo");//system.out.println (D.getname () );//d.run ();d. Start (), for (int x =0;x<60; x + +) {System.out.println (Thread.CurrentThread (). GetName () + "---main---" +x);}}}

  

/*
The main function is also a thread whose name is called Main, which is generally called the main thread.
The names of the other threads can be assigned when they are created, or the thread-number if the default name is used.
The difference between run () and start ():
The Run method is only used to store the code that the thread needs to run.
The start () method is used to open the thread, and only the thread is turned on, and the system allocates resources other than the CPU to the thread. The Run method is then called.
*/

Black Horse Programmer _ Multithreading Summary

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.