The Java self-study road-DAY17

Source: Internet
Author: User

JAVA17

Conceptual processes for multithreaded processes and threads

L programs that are running

L program is stored in the hard disk when running into memory

L Every program in memory is called a process.

L and each process has a separate function

Thread

L multi-threaded download in thunder

There are many ways to arrange one at a time in the Main method

    1. If one of the methods performs many loops
    2. Then the next method will not execute
    3. From the entrance main to the end, a way to go in the end must be one of the execution
    4. This procedure is a single threaded program
    5. Slow efficiency

L For example

Internet cafes in multiple computers

Multiple Road traffic

Threading Concepts

L CPU Central Processor Inter AWD

L Quad Core Eight threads

L 360 anti-virus tools

    1. Enter memory
    2. There is a process 360safe.exe
    3. All functions into memory
    4. All functions are a method in the program
    5. All functions can be run separately at the same time
    6. All functions run by the CPU
    7. A new execution path is opened for each CPU that opens a function
    8. Which means a new thread.
    9. An early CPU can only perform one thread at a time. Cycle switch Run
    10. The current CPU has more than one core so that multiple threads can be executed at the same time

Thunder Download

L Multi-Threaded download

L did not improve the speed of the internet but multithreading increased

Running mode time-sharing scheduling for threads

All threads use CPU resources in turn to evenly allocate CPU time to a thread

Preemptive scheduling

High priority multi-use random selection with the same CPU resource priority as one for scheduling

L

Main thread

L Compile

L JVM runs the Main method

L Find operating system thread

l have an execution path for the CPU the main path has a name, main.

L This is the main thread.

L multithreading even if one thread is wrong other threads will execute

Thread class overview

L Java.lang in Bag

L JVM allows programs to run multiple threads

• Each thread has a priority

L Create threads with two methods

    1. Inheriting the thread class overriding the Run method
    2. Implementing the Runable interface implementation of the Run method
Implementing Thread Inheritance Threads

L define a class to inherit the thread override the Run method

L Instantiate an object of this class in a test class call the Start method

L Start method can only be performed once

l The order of execution is not the same as before

L graphic

    1. JVM opens main main thread
    2. CPU Run main thread
    3. A new thread has been opened in the running method
    4. CPU executes new thread
    5. Resume the Start method to start a new thread prepare to execute the Run method
    6. The CPU has two execution paths
    7. The CPU itself controls the loop that runs the main method or the Run method
    8. CPU allocates time slices to threads

Why to inherit thread

L Call the run and start differences

    1. Start to open the thread and let the JVM call the Run method running in the open thread
    2. Run is a way to wait to be executed no other function

The thread class inherits this class is the thread class

L Create the thread class object directly, the Run method is the method of this class, there is no operation can not run the custom code, so we need to inherit this class to rewrite the Run method and then execute the code we need to execute in another thread

The function of the Run method is to execute the code we want to execute in the new thread

Memory graph of threads running

L Main method advanced into

L then call the Start method Run method ready to be called by the JVM

L Run method does not enter this stack will open a new stack space to execute the Run method separately

L

Get Thread Name

L Main main thread name is main

L console Gets the default thread name

L GetName Get thread name

Calling the parent class method can not write super

L Get main thread name

Static Thread CurrentThread ();

Gets the name of the thread that is running this method returns the thread type

Simplified

Set the thread name

L SetName ()

    1. Need to rename in the main thread
    2. Main thread name cannot be changed

L Construction Method rerouting name

    1. There is a constructor in the parent class that can be changed by name

Sleep method

L thread stops at a specific time

L Throw exception

This exception is thrown when awakened during hibernation

Runnable interface

L Another way to implement threading

L Implement Interface Runnable

L Implementation Method Run

Example
    1. Create an interface implementation class first
    2. The thread object is then created to pass the implementation class object
    3. Then call the Start method
Principle

    1. Thread has a constructor method that can pass in the Runnable type Object
    2. Define a class implementation runable interface new object in the constructor of the incoming thread, you can open a new thread to run the code
    3. Avoids the limitations of single inheritance
    4. Thread is part of a thread object that is divided into two parts is a thread task
    5. Thus reducing the coupling degree
Benefits

Anonymous inner class implements thread

L Premise inheritance or interface implementation

L New parent class or interface implementation () {overriding abstract method}

l Example

    1. Inherit thread

    1. Implementing interfaces

State diagram of a thread

L New State

L RUNNABLE The running state is executing this thread in the JVM virtual machine

L BLOCKED Blocked

Deadlock CPU Resource was robbed

L waitting wait for infinite sleep

Methods in the Object class

L Timed_ waitting Sleep

L treminated Death Status

L blocked resources that have CPU execution eligibility waiting for CPU

L hibernate wait thread abandons CPU's execution qualification

Thread Pool Overview

L is a container that can hold multiple threads

L Create multiple threads to be stored in the collection at the beginning of the program

L Use the Remove method to remove the thread and add it again with add

L've been developing thread pools myself before.

L Jdk1.5 after adding thread pool technology

Using the thread pool mode runable interface

L created by thread pool factory

L re-call method in thread pool to create thread

L Executors Class

    1. Java.util.concurrent Bag
    2. Method

A) Create multiple

b) Create a single

c) The return value is the thread pool class object

    1. Example

The console does not stop when the thread runs out and has returned to the thread pool

Thread Name

Stopping a thread

Shutdown Thread Stop

Implementing Thread Callable Methods

L Runnable interface thread runs out no results can not throw exception

L Jdk1.5 after a callable interface call method is equivalent to run

L Call method has return value can throw exception

L Create thread pool objects first with factory class static method Newfixedrhreadpool

L Thread Object Call method submit thread task passed in a callable interface implementation class

l Example

Parent interface throws an exception subclass to throw an exception or throw an exception

Practice

L Asynchronous computation

Thread operations shared data security issues ticketing example

Multiple threads running concurrently running a piece of code at the same time

L The result of each run is the same as single-threaded run results

L Ticketing

L multiple ways to purchase tickets multiple threads operate the same data

L should update the data at the same time otherwise there will be security issues

l Example

Data is OK but there are security implications

Security issues raised

L T0 judgment is ready to begin operation

L CPU is preempted by T1 thread at this time

L T1 The judgment is ready to be operated

L was preempted by T2 thread at this time

L T2 The judgment is ready to be operated

L CPU resources get T0 to perform operations at this time – data is 0

L T1 also executes-data is-1

L T2 also executes--data is-2

• Thread safety issues occur

L Simulation Example

    1. Pause before execution sleep

Solve
    1. Synchronizing code blocks
    2. When a thread enters the data operation is no matter whether it sleeps other threads can only wait
    3. Sun provides a technology to achieve such a solution
    4. Formula

Synchronzied (arbitrary object) {

Shared data for thread operations

}

    1. Synchronizing code blocks
    2. Example

Cannot write anonymous object

It's getting safe.

But it's slowing down.

Principle of execution

L Synchronization Object Arbitrary object

L Object: Sync lock Object Monitor

L Synchronous guarantee Security The thread that is not locked cannot execute only wait

L The thread encounters the synchronization code block and then determines if the sync lock has

L if not, wait.

L Set the sync lock to 0 if there is a get lock

L Enter the synchronization code block at this point, if you hibernate

L Another thread came over to execute the code will determine if there is a synchronization lock is obviously not at this time, so I can't get into the code block can not execute code

L Continue executing code and releasing the sync lock if the first thread wakes up

l so a thread needs to judge the lock to get the lock release lock, so it's been extended for a long time.

L Synchronous lock principle and toilet

    1. The object is the toilet door.
    2. A sync lock is a lock on a toilet door.

Multiple threads accessing a shared data will set a sync lock

Synchronization method

L Code Concise

L Extract thread-sharing data and synchronization into a single method

The declaration of the L method plus the Sync keyword and then delete the sync no code block

L StringBuffer have this kind of synchronization method. Slow Running

L StringBuilder is a thread unsafe to run fast

Does the sync method have a lock?

    1. There must be.
    2. Object locks are object references to this class

L If the method is static

    1. A lock in a static method is not a reference to this class object
    2. Static is not part of an object reference
    3. The object lock in a static method is the class name. class

    1. The principle of reflection is involved
JDK1.5 New Lock interface

L RELEASE the sync lock, I can't see it.

L will not release if the code has an abnormal lock

L Therefore the lock interface appears after JDK1.5

L This interface provides a wide range of locking operations that can be obtained with more methods and statements than using synchornized

l Example

    1. Interface method

Lock get Lock

Unlock release lock

    1. Implementation class

Reentrantlock

    1. An implementation class object that creates a lock interface on a member variable by implementing a class
    2. Call the lock method to get the lock before the code to be locked
    3. Call the Unlock method to release the lock after the code to be locked
    4. If there is an exception, write Unclock in the finally code behind the exception to ensure that the lock is released normally when the exception occurs
Dead-Lock principle

L Sync Lock and write a sync.

An infinite wait has occurred in the program

L Prerequisite must be multi-threaded synchronous nesting

L thread into sync get lock not out sync won't release lock

L First person needs a second person's lock. The second person has the lock that needs the first person

L

Simulation implementation

L Define two lock objects a B

    1. Need to define two classes
    2. and to establish a private construction method is that the outer class cannot create a new instance
    3. Then provide a static final object for the outer class to use directly but not to change

L loop with odd even to determine thread 1 and thread 2

L then a test class

    1. Create two threads to execute the Run method

L Program Run Results program will never stop running

    1. The first few times have been successful.
    2. The last two times the first time to execute even loop, acquired a lock, but did not enter the B lock, is an odd loop preemption, acquired a B lock
    3. This is the first time a B lock is required to continue execution the second time requires a lock to continue execution
    4. Then no one can get the resources they need, so they're locked up.
Thread Wait and Wake overview

L also called thread communication

L Multiple threads handle the same resource

• Each thread task is different

L If we want to use resources rationally

L need a means to enable each thread to effectively utilize resources

L This method is called the waiting wake mechanism.

L For example, before the ticket sales, there are now threads that need extra tickets.

Example

L Resource Class

    1. Define a public two member variable

L Two thread class input and output

    1. Input

    1. Output

L Test Class

Because there are two of objects

L Resolve

    1. Write private object in deadlock resource class let outer class call new instance by calling
    2. To write a constructor for an acceptable resource class object in the input class and input class
    3. Then in the main method, create a new resource class object in the constructor of the incoming output class and the input class
    4. Results

    1. There was a sex mess.

L Resolve

    1. Problem emergence principle

A) Input class grabbed the CPU to assign a value to three men

b) The output of the assignment is not grabbed by the CPU

c) The input class still grabs the CPU to assign the value Lisi

D) The Lisi has not yet been assigned a value of NV

e) Output class The CPU resources are directly output Lisi NV

f) There is a gender mess at this point

    1. Solve

A) There is only one way to add a synchronous lock

b) Find shared data

c) lock in the input class

Output class Join Lock

It's still not solved.

L Resolve

    1. Reason

A) Two threads are not the same lock

    1. Change object lock this to object lock for resource object R
    2. The result solves the problem

Case analysis

L final target one input one output alternately appears

The thread will only execute the Run method without assigning values and values

L The ideal state should be one-time assignment printing

L The next assignment only starts after the last assignment output

L must wait for the next input to finish before outputting

L Implementation Steps

    1. Input: Execute method After assignment wait Wait forever
    2. Output variable value printout after notify input wake up then output execute wait Wait forever
    3. Input: After being awakened, the thread that must wake the output botify input wait after the variable assignment is re-assigned value
Realize

L Get CPU execution first to ensure program execution input

L Add a variable to the resource class, Boolean flag

L Flage Assignment Complete for true description

L Flage for false instructions get value complete

L input needs to determine if the tag flage is true

If it is true, wait.

If False, assign the value and change the token to False

L output is also true

l Example

    1. Add Variable Value

Input

Output

The result throws an exception

Abnormal

That means the wake-up and wait method callers are wrong.

Should be a lock object call

Modify

L Results

The Java self-study road-DAY17

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.