Java Basics Summary-Multithreading Summary 1

Source: Internet
Author: User

----Processes and Threads-----
1. Overview: A simple understanding of a process is a running program (the space in which the program is stored)
The program is loaded into memory only when it is running
2. Intra-Process Division
The process does not execute directly, but is treated as the basic unit of allocating memory resources, the real execution unit is the thread (execution path), a process contains at least one thread, multiple threads represent multiple tasks, multiple execution paths can run concurrently, so there are certain constraints between them eg: There may be multiple threads that work together to complete a task, possibly accessing a resource in a sequential relationship. Loader code into memory--executes from a portal
3. The meaning of Multithreading: Concurrent execution, multiple tasks can be performed concurrently over a period of time
Note: Concurrency does not perform multiple tasks at the same time, micro-serial, macro-parallel. CPU Control program running, responsible for scheduling thread operation (time slice scheduling thread execution-time slice is very short)
If there are two CPUs, you can do real parallel execution at this time--the disadvantage or not enough memory
4. Advantages and disadvantages of multithreading
Advantages: Ability to solve concurrent execution of multiple programs over time
Disadvantage: Multi-Threading is CPU-scheduled waiting time to add more
5. There is currently only one thread-the main function thread (which must depend on the execution of the thread), garbage in the heap, garbage collection thread
When the JVM is turned on, multiple threads are started eg: main thread, garbage collection thread, etc.
When a thread's task executes, the thread ends and the JVM waits for all threads to end before the JVM exits
6. The garbage collector does not recycle as soon as it encounters garbage, but first determines the size of the heap memory and determines whether or not to recycle heap memory based on memory size
7. Main thread--only when there is only one execution path, the program executes in the order in which the code is written (the method call is a thread), the JVM determines that no other content is directly shutting down the process
8. When you might think of using multithreading
A-->b-->c in this order, but the B event requires a large cycle time, so at this point a custom thread is used to complete the C time execution

-----Multithreading-specific learning-----The underlying execution is system-dependent (the method inside the thread is basically a system-related local method)
Note: about why you should inherit the thread class instead of creating the thread class object directly
The reason is: to create the thread in order to create the execution path, the main thread of its tasks are defined in the main method, the custom thread of its corresponding task should be defined in the thread class definition of the run () method, so different threads have to do special tasks, you must rewrite run (), In turn, you must inherit the thread class.

-----How to create a thread------
* Inherit the thread class (already implemented Runnable interface), override the Run method
Creates an object of the thread subclass, starting the Thread object. Start () and tell the JVM to automatically invoke the object's run () method
Note: calling run () with a subclass object is not a startup thread at this time, but a method call
The CPU transfer thread is random, so the result of the execution is random.
GetName () Gets the name of the thread object
Thread.CurrentThread () Gets a reference to the currently running thread object
* Multi-threaded operation diagram
Creating a thread---Creates a separate path (equivalent to each line threads occupies a fixed space in the process's memory space, freeing up space after the thread has finished executing)
Eg: there are 3 threads whose names are three-to-three, they are executed separately, they each execute their own content (if)
If the main thread is abnormal, it will not execute itself, and will not cause the execution state of other threads to change.
Who has an exception, the thread ends---used to analyze multithreaded security issues
When do-----use multithreading----
A code to be executed at the same time, such as a print loop, can be executed using threads to implement the code.
Let the class inherit the thread class, overriding run () {The code that was executed more than once}.
The problem arises: if the class and inheriting a parent class cannot inherit the thread class, you can use the second way to create the thread.
* Define the class implementation runnable interface, override the Run () method, create a thread object to accept the subclass object of the Runnable interface
(Interfaces can extend the functionality of a class)
MyThread Implements runnable{
public void Run () {thread body;}
}
MyThread MT = new MyThread ();
Thread t = new Thread (MT);-There is polymorphic t.start ();
The second design idea: holding the reference to the interface (invoking the construction method of the second construction thread object)-see the source code
The second way to create threading benefits
* Inheriting the thread () class in the first method, in fact just want to use the run () method, and do not want to inherit all the methods inside the thread class, we can directly implement the interface runnable (just rewrite a run method can be)
* Second good in cases where the class that is being executed multiple times already has a parent class, select Implement interface--avoid single-threaded limitations
So the second way to create threads is more common
* The thread class also implements the Runnable interface

State conversion of------threads-------
1. The created state---become a thread object
2. Call start is started to be ready--waiting for the CPU to be dispatched--there is the qualification to be executed
3. If the CPU is transferred--it becomes a running state--cpu is processing the thread
(Ready-run-run-ready (wait for the event to occur/call sleep to sleep for a certain amount of time)--block blocking (awakened by another object)--ready) Call the Wait/notify method through the object (method inside object)
Call Sleep () to give up the CPU's execution, wait until you wake up, and then continue to queue up for scheduling in the Ready team
Note: Sleep () is inside that thread body, and that thread sleeps
4. Blocking status: Release execution is scheduled by CPU, discard execution qualification
5. Thread death: Thread is forced to end stop/thread body execution is done
6. An exception occurs after a thread starts---cannot be restarted repeatedly

------The problem of multithreading security------
Four tickets sold out-multi-threaded simultaneous execution--
1. Method One processing: inherits the thread class, at which time Num will be present in 4 thread objects, total 400 votes
Can handle num--statically but that's not quite the problem.
2. Method 2 handles the implementation interface, but only creates a ticket object, so the total number is 100 votes
3. Causes of multithreading security issues
* Multi-threaded operation sharing data
* There are several codes for manipulating shared data
* When a thread is working on multiple code sharing data, another thread is involved, causing a thread safety problem
------Solutions to multithreading problems-------
The essence is to prevent a thread from participating in another thread while it is manipulating the shared data.
The specific design:
is to encapsulate the code of the multithreaded operation to share the data, and when the thread executes the code, no other threads are allowed to access it, and the other thread can access it only after the threads have finished executing.
1. Object lock synchronized decorated code block--Synchronous code block--To achieve synchronization
Specific format synchronized (object) {The code that needs to be synchronized;}
Object--this/any other object
Observation: Only part of the thread is printed-the reason is that other threads are not taking the opportunity to execute
2. Modification Method--synchronous method (need to be executed in order)---Lock is the object that this method belongs to--is also a kind of encapsulation
The lock is the object that the method belongs to--this
You can let threads use synchronous blocks of code, and thread 2--use synchronous methods, so long as they are locked to the same this, thread synchronization can be implemented:
Note: eg: the specific implementation process of the ticket sales example:
1. Create 2 ticket-selling threads, as well as the existing main thread
2. The main thread runs, start thread 1, the main thread sleeps out of CPU execution, thread 1 get execution, hold this lock into the Run method inside, first hibernate (the process will not release the lock), wake up to continue to execute (or), after the CPU allocated time slice end, let the CPU execute right.
3. The main thread modifies the flag parameter, thread 2 starts and gets execution may execute to the end.

-----The difference between a synchronous code block and a synchronous method-----
The object lock of the synchronization function---This
The lock---of a synchronized code block can be any object
Synchronous code blocks are recommended for general comparison

----The lock----of the static synchronization function
Static sync function Lock: The bytecode file of the owning class is encapsulated as object of class type--Bytecode file object
How to get the object: This.getclass ()/thicket.class (the bytecode file object has a static attribute class)

----The premise of synchronous use----
Synchronization does not resolve all thread safety issues, it solves the problem must have the following two points
1. There are multiple threads in the program
2. Ensure that multiple threads access the same resource with the same lock, otherwise there is no guarantee that a thread will have access to the resource without other threads.
3. Lock: In fact, the essence is to ensure that the thread is scheduled by the CPU, the execution of the process will not exist other threads into
(regardless of any situation-when the sleep/time slice is exhausted, as long as the thread is in sync, it is guaranteed that only one thread is in it--once out of sync other threads will be able to enter the synchronization if they get the scheduling right)
4. Multiple threads accessing shared resources have security implications, not every time security issues occur

---single case design mode and multithreading security----
Single Case design mode
1. Lazy type-Lazy load singleton mode, first create a reference, call the Get method, then create the object--compare recommended
2. A hungry man-create an object that provides a public way to return the object
3. For the lazy single-case---plus a synchronous method, each time to determine the lock, the cost of time, so add synchronization code block, will first determine if you have created an object, do not judge the lock, directly get a singleton object.

---deadlock----
1. One of the common forms of synchronous nesting--thread A in the case of a lock, also need a b lock, and thread B in the case of a B lock, also need a lock, two threads do not want--resulting in two threads can not go on

Java Basics Summary-Multithreading Summary 1

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.