java-Multithreading Basics

Source: Internet
Author: User

java-Multithreading Basics
A related concept
Process: is an executing program
Each process has an order of execution, which is an execution path, or a control unit

Thread: A separate control unit in a process that controls the execution of a process

Note:
A process has at least one thread

A Java VM will start with a process Java.exe
At least one thread in the process is responsible for the execution of the Java program, and the code that this thread runs is in the main method
This thread is referred to as a main thread

The JVM starts more than one thread, and a thread that is responsible for the garbage collection mechanism

Two custom Create threads
Need to use the thread class
Create method One :
1. Define class inherits from thread

2. The Run method in the replication thread

3. Call the thread's Start method, which has two functions: Start a thread, call the Run method

Create method Two:
1. Define class implementation Runnable interface

2. Overwrite the Run method in the Runnable interface

3. Creating thread objects through the thread class

4. Pass the subclass object of the Runnable interface as the actual parameter to the constructor of the thread class:
The reason is that the object that the custom run method belongs to is the subclass object of the Runnable interface
So to get the thread to specify the object's Run method, you must explicitly define the object that the Run method belongs to.

5. Call the Start method of the thread class to open the thread and invoke the Run method of the Runnable interface subclass

two different ways to differentiate:
the benefits of method two implementation: avoid the limitations of single inheritance, and recommend the way to implement it

Multi-Threading features: randomness, due to the CPU's time-sharing scheduling rules (at a certain moment, the CPU only runs a program, the CPU in the process of running a fast switch), as for the execution of the timing, the CPU said the calculation

object calls the difference between run and start:
Start: Open the thread and execute the thread's Run method
Run: Only the object is calling the method, and the thread is created and not running

multi-threaded running state:
Create, run, perish, block, freeze
Such as:

Common methods of Multithreading:
Static thread CurrentThread () Gets the current thread object
GetName () Gets the thread name, the default format of the thread name is Thread-0 (...)
SetName or constructors can set the thread name

Three multi-threaded security issues:

Resolving the time lag problem with thread operation data requires
1, synchronizing code blocks

synchronized(对象锁){    需要同步的代码;}

2, Sync function
is to add the Synchronized keyword to the function.

publicsynchronizedvoidTest(){}

How to find the security risk of the thread:
1. Identify which code is multithreaded to run the code
2. Clearly shared data
3. Define which statements in a multithreaded run code are operations that share data

Three Locks
Lock:
A lock is an object
the locking of the synchronization function is this,
The lock of a static synchronization function is the bytecode file object of the class in which the method resides. Class name. Class object: The static method cannot define this, the static method enters memory, and there are no objects of this class in memory
But there must be a byte-code file object of that class, class name. class, the type of the object is class

Deadlock: Two threads competing for a lock

Here is an interview question: Write a deadlock Demo

 class Test implements Runnable{    Private BooleanFlag Test (BooleanP_flag) { This. flag = P_flag; } Public voidRun () {if(flag) { while(true) {synchronized (Mylock.locka) {System.out.println ("If Locka"); Synchronized (mylock.lockb) {System.out.println ("If lockb"); }                }            }        }Else{ while(true) {synchronized (mylock.lockb) {System.out.println ("If lockb"); Synchronized (Mylock.locka) {System.out.println ("If Locka"); }                     }            }        }    }}//Lock Object class MyLock{    StaticObject Locka =NewObject ();StaticObject lockb =NewObject ();} class testdemo{     Public Static voidMain (string[] args) {Thread T1 =NewThread (NewTest (true)); Thread t2 =NewThread (NewTest (false));        T1.start ();    T2.start (); }}

four multi-threading vs. Singleton design mode:
The main problem is the lazy type :

Class Singel {Private StaticSingel s =NULL;Private Singel(); Public StaticSingelgetinstance()    {//Double judgment can solve the problem of low efficiency        if(NULL= = s) {//synchronized keywords are more efficient than synchronizing on functions            synchronized(Singel.class)//Use the lock for this type of file{if(NULL= = s) {s =NewSingel (); }            }returnS }    }}

The code above needs to remember that the interview may ask

Copyright NOTICE: Welcome to communicate the error of the article, must humbly accept, QQ872785786

java-Multithreading Basics

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.