Multithreading (thread)
* Process
* Thread (for example, flashget and thunder)
* Meaning of Multithreading
* Thread Creation Method
* Multithreading features
Process: A program in progress.
Each process has an execution order.
The sequence is an execution path (scenario) or a control
Unit.
Thread: it is an independent control unit in the process.
Controls the execution of processes.
A process has at least one thread.
Java JVM starts with Java. EXE.
At least one thread in the process is responsible for Java program execution.
The code run by this thread exists in the main method.
This thread is called the main thread.
Extension: in fact, more details about JVM. JVM starts more than one thread.
And the thread responsible for the garbage collection mechanism.
1. How to customize a thread in custom code?
By searching APIs, Java has provided thread-related services.
The description of the object is the Thread class.
The first way to create a thread: Inherit the Thread class
Steps:
1. Define class to inherit from thread;
2. re-write the run method in the Thread class
Objective: To store custom code in the run Method
To run the thread.
3. Call the start method of the thread. This method has two functions:
1. Start the thread; 2. Call the run Method
Example:
Class demo extends thread
{
// Overwrite the run Method
Public void run (){
Syso ("demo run ");
}
}
Class threaddemo {
Public static void main (string []
ARGs ){
Demo d = new demo (); // create
Threads
// D. Start ();
D. Run ();
* ******* Interview ******
Run (): it is just an object call method. While thread Creation
Created and not run.
Start (): Start the thread and run it.
Method.
}
}
It is found that the running results are different each time.
Because multiple programs are obtaining the CPU execution right. Who is the CPU running?
.
It is clear that only one program is running at a certain time.
(Except multi-core CPU)
The CPU is performing a quick switch to make it seem to be running at the same time.
.
We can image the multi-thread running behavior to snatch the CPU from each other.
.
This is a feature of multithreading: randomness.
Why overwrite the run method?
The thread class is used to describe the thread.
This class defines a function for storing the generation of threads to run.
The storage function is the run method.
That is to say, the run method in the Thread class is used to store
The code to run.
Example:
Create two threads and run them alternately with the main thread.
Class test extends thread
{
Public void run (){
For (INT I = 0; I <60; I ++ ){
Syso ("Test Run" + x );
}
}
}
Class threadtest {
Public static void main (string []
ARGs ){
Test T1 = new test ();
Test t2 = new test ();
T1.start ();
T2.start ();
For (Int J = 0; j <60; j ++ ){
Syso ("Main..." + x );
}
}
}
Thread creation method 1
Inherit Thread class
1. The subclass overwrites the run method in the parent class and runs the code of the thread.
Stored in run.
2. The thread is also created when a subclass object is created.
3. Enable the thread by calling the start method.
The first State of the thread: created, inherited from the thread
The second State of the thread: frozen. The thread can run as soon as the time reaches.
(Sleep (time ))
The third state of the thread: frozen, but cannot run by yourself ,(
Wait waits for itself to return (), y wake up (); give up
Execution qualifications. First, return to the temporary status from the frozen state, and then execute
Line.
The fourth state of a thread: extinction, stop (), and end of the run Method
.
Special Thread status (temporary (blocking) status): Running
Qualification, no execution right.
All threads have their own default names.
Getname () method // obtain the thread name. Set the thread Name:
Setname or constructor.
Thread. currentthread () method // get, current thread
Object. Static. Common Mode.
/*
Requirement: simple ticket selling procedure.
Sell tickets in multiple windows at the same time.
*/
Class ticket extends thread
{
// Static, generally not static, lifecycle
Too long
Private Static int tick = 100;
Public void run (){
While (true ){
If (tick> 0 ){
Syso (thread. currentthread
(). Getname + "... sale:" + tick --);
}
}
}
}
Class ticketdemo
{
Public static void main (string []
ARGs ){
// ***************** 1st. Type
Ticket T1 = new ticket ();
// Ticket t2 = new ticket ();
// Ticket T3 = new ticket ();
// Ticket t4 = new ticket ();
// Running exception: Invalid thread startup exception
T1.start ();
T1.start ();
T1.start ();
T1.start ();
// ************* How can this problem be solved? Method 2
}
}
The second way to create a thread is to declare and implement the runnable interface.
Class, which then implements the run method. Then the class can be assigned.
The instance is passed and started as a parameter when the thread is created.
. The same example using this style is as follows (JDK ):
Class primerun implements runnable {
Long minprime;
Primerun (long minprime ){
This. minprime = minprime;
}
Public void run (){
}
}
Method 2 for thread creation: implement the runnable interface
Steps:
1. Define the class to implement the runnable interface
2. overwrite the run method in the runnable interface
Store the code to be run by the thread in the run method.
3. Create a thread object through the Thread class
4. Pass the subclass object of the runnable interface as an actual parameter
Constructor of the thread class.
Why do we need to pass the subclass object of the runnable interface?
To the constructor of the thread.
Because the object to which the custom run method belongs is
The subclass object of the runnable interface. So let the thread specify
Set the object's run method. You must specify the pair to which the run method belongs.
Image.
5. Call the start method of the thread class to enable the thread and call
The run method of the subclass of the runnable interface.
* ***** Interview ****
What is the difference between implementation and inheritance?
Benefits: This avoids the limitations of single inheritance.
We recommend that you use the implementation method when defining a thread.
There are two differences:
Inherit thread: the thread code is stored in the run method of the thread subclass.
.
Runnable implementation: The runparty with the interface words in the thread code
.
-------------------------------------
Another simple program for ticket sales:
Through analysis, it is found that the wrong tickets except 0,-1,-2 are printed.
Security problems occur during multi-threaded operation.
Cause:
When multiple statements operate on data shared by the same thread
A thread only executes a part of multiple statements and does not execute
Another thread participates in the execution after the row ends, resulting in an error in data sharing.
Error.
Solution:
Only one statement can share data for multiple operations.
When all threads are executed, other threads cannot
And execution.
Java provides professional solutions to multithreading security issues
. The synchronization code block is as follows:
Synchronized (object ){
Code to be synchronized
}
Objects are like locks. The thread holding the lock can be executed in synchronization. No
A thread holding a lock cannot even obtain the execution right of the CPU.
Because no lock is obtained.
Prerequisites for synchronization:
1. There must be two or more threads.
2. Multiple Threads must use the same lock.
*******************
Ensure that only one thread is running in synchronization.
Benefit: it solves the security problem of multithreading.
Disadvantage: multiple threads need to judge the lock, which consumes more resources.
One is the synchronous code block;
One is a synchronous function.
* ***** Which lock is used for Synchronous functions?
The function must be called by an object. The function has an object.
Reference, that is, this. So the lock used by the synchronous function is this
.
If the synchronization function is modified by a static function, what is the lock used?
What about it?
It is not this, because this cannot be defined in static methods.
When static memory is entered, the memory does not contain this class object, but there must be
The object of the bytecode file corresponding to this class.
Class Name. Class the object type is class.
Static synchronization method. The lock used is the byte of the class to which the method belongs.
Code file object. That is, the class name. Class (unique)
Class ticket implements runnable
{
Private Static int tick = 100;
// Object
Object OBJ = new object ();
Public void run (){
While (true ){
// Synchronize code blocks (flag lock)
Synchronized (OBJ ){
If (tick> 0 ){
Syso (thread. currentthread
(). Getname + "... sale:" + tick --);
}
}
}
}
}
Class ticketdemo
{
Public static void main (string []
ARGs ){
// The created thread is not
Ticket T = new ticket ();
Ticket T1 = new ticket (t );
Ticket t2 = new ticket (t );
Ticket T3 = new ticket (t );
Ticket t4 = new ticket (t );
T1.start ();
T2.start ();
T3.start ();
T4.start ();
}
}