1, multi-threaded implementation of two ways
(1) Inherit thread
- Define class inheritance Thread
- Overriding the Run method
- Write what the new thread is going to do in the Run method
- To create a thread object
- Opens a new thread, and the Run method is automatically executed internally
(2) Realizing runnable
- Defining a class implementation runnable interface
- Implementing the Run Method
- Write what the new thread is going to do in the Run method
- Creating a child class object for a custom runnable
- Create thread object, incoming runnable
- Call Start () to open a new thread, internal automatically calls Runnable's Run () Method 2, multithreading security issues and solutions
Problem: When multiple threads are concurrently executing, the data can become garbled.
Scenario: We want a piece of code to perform during a process in which the CPU does not switch to other threads to work. This will require synchronization.
3, the production principle of the deadlock
Multi-threaded synchronization, if the synchronization code nesting, using the same lock, there is a possibility of deadlock
4, multi-threaded implementation of two different ways
Implementation principle:
Inherit thread: Because the subclass overrides the thread class's run (), when Start () is called, the Run () method of the subclass is searched directly
Implement runnable: A reference to the runnable is passed in the constructor, the member variable remembers it, and the start () call to the run () method internally determines whether the reference to the member variable runnable is empty, and does not empty compile-time view of the runnable run (). Run-time execution is a subclass of the run () method
Advantages and Disadvantages
Inherit thread:
Benefit: You can use the methods in the thread class directly, the code is simple
Cons: If you already have a parent class, you can't use this method
Implement runnable:
The benefit: Even if the thread class you define has a parent class, it doesn't matter, because the parent class can also implement the interface, and the interface can be implemented more
Cons: Cannot use the method in thread directly need to get to the thread object before you can get thread method, code complex
Topic 24-Multithreading two ways to implement