Java Multithreading Knowledge Collation

Source: Internet
Author: User

First, the conceptProcess--In progress programs.

Thunderbolt when downloading a file divided into 5 parts, is to compete with the CPU resources.
Split 5 parts, each part called a thread.

a thread is a control unit in a program, or an execution path.
Each process execution has an execution sequence, which is an execution path,

Each program opens, allocating a piece of space in memory.
Process is to define, identify the space, it is used to encapsulate the control unit inside.

A thread is an independent control unit in a process that controls the execution of a process.

There is at least one thread in a process, and the thread is the content in the process.

There will be a process when the JVM starts Java.exe
At least one thread in the process is responsible for the execution of the Java program,
And the code that runs on this thread exists with the main method.
This thread is called the primary thread.

Extended:
in fact, more details indicate that the virtual machine JVM,JVM boot more than one thread, as well as a thread responsible for the garbage collection mechanism.

The meaning of Multithreading:
To make the code run at the same time, it is easier to perform.


The thread class: A class used to describe things like control units (threads).This class defines a feature that stores the code that the thread will run, which is the Run method.
This means that the run method in the tread class is used to store the code that the thread will run.

Processes, threads are created by the system, and Java has provided a description and representation of this kind of operation.


There are two ways to create a new thread of execution:
1. Declare the class as a subclass of tread, which should override the Run method.
Why would you rewrite the Run method?
Purpose: Store the custom code in the Run method and let the thread run.
2, implement Runnable interface, overwrite the Run method.
Pass the subclass object of the Runnable interface as a parameter to the constructor of the thread.

What is the difference between an implementation and a way of inheriting?
Inherit thread: The threading code is stored in the threads subclass Run method.
Implement runnable: Thread code exists in the subclass of the interface Run method.
Benefits of the implementation approach: avoids the limitations of single inheritance.
When you define a thread, you establish how it is implemented.

Note: If you just call the Run method, you cannot implement multithreading. Because the thread is not turned on.
The Start method has two functions: to open a thread and execute the thread's Run method.

Know:
Some early viruses were turned on n multithreading "robbery" CPU resources caused the crash.

Multithreading seems to realize the execution of the program at the same time, in fact, the CPU is doing a fast switch.
Features of Multithreading: randomness.

Know:
Multicore can be implemented simultaneously, provided the memory is large enough.


four states of the thread:
Start () Sleep (Time)
Created---------> Run-----------------> Freeze: Waiver of execution eligibility
| Wait ()
| Stop () or Run method ends
└------> Extinction
Fifth state:
Temporary status
Blocked: qualified for operation, but no execution right

Sleep: The time will run automatically
Wait: Need someone to wake up the--notify method


Methods of threading:
|---getName (): Returns the name of the thread Tread-0, starting from 0
|---setName (): Sets the name of the thread.
|---You can set the name directly in the construct.
|---currentthread:static returns the currently executing thread object


Problems with Multithreading:
Write multithreading must be careful about security issues.

When multiple statements are working on the same thread to share data, a thread is only
Executes a part, has not finished executing, another thread participates in the execution, resulting in a total
To enjoy data errors.

Workaround:
Statements that share data on multiple operations can only have one thread complete.
During execution, other threads are not allowed to participate in execution. --Synchronizing code blocks.

Synchronized (object) {
Code that needs to be synchronized
}


The object is like a lock, and the thread holding the lock can execute in the synchronization.
A thread that does not have a lock, even if it gets the execution of the CPU, cannot get in because the lock is not acquired.

Prerequisites for synchronization:
1. You must have two or more threads.
2. The same lock must be used by multiple threads.

Benefits: Solves the problem of multithreading security,
Cons: Multiple threads need to determine the lock and consume more resources.


How to find a problem:
1, clear which code is multithreaded running code.
2. Clear sharing of data.
3. Clear which statements in multithreaded run code are operations sharing data.

Synchronization functions
Public synchronized void Add (int i)
function needs to be called by the object, the above with the synchronous function is not passed the object, the default is this

Note: If the sync function is statically repaired, what is the lock used?
This is not the case anyway, because this is not defined in a static method.
Static into memory, there is no such object, but there must be a corresponding byte of the class file object.
Class name. Class The type of the object is class.

Single-instance design pattern lazy security issues:

Solution:

Class Single{private Static single S=null;private A () {}public static single getinstance () {if (s==null) { Synchronized (Single.class) {if (s==null) {s=new single ();}}}}


Interview Test Centers:The lazy type is characterized by delayed loading.
When using multi-threading, there will be security risks, which can be resolved by synchronization, but less efficient,
This inefficient problem can be solved with multiple judgements, with the byte-code file object that the class belongs to.

Deadlock:
Synchronization is nested in sync, but locks are different.

Deadlock Program:

Package Demos;public class Demo_06 {public static void main (string[] args) {new DeadLock (false). Start (); New DeadLock (True ). Start ();}} Class DeadLock extends Thread{private Boolean flag=false;deadlock (Boolean flag) {This.flag=flag;} @Overridepublic void Run () {if (flag) {synchronized (Lock.locka) {System.out.println ("if Locka"); synchronized ( LOCK.LOCKB) {System.out.println ("if lockb");}}} Else{synchronized (lock.lockb) {System.out.println ("Else Locka"); synchronized (Lock.locka) {System.out.println (" else lockb ");}}}} Class Lock{static Object Locka=new object (); Static object Lockb=new object ();}














Java Multithreading Knowledge Collation

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.