I will first write an outline, which is divided into the following modules:
1. Two Methods for creating threads in Java
2. Substantive and usage differences between the two methods
3. thread status
4. Synchronized Locking Mechanism
5. synchronization between threads
Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1. Two Methods for creating threads in Java
In Java, there are two methods to implement the thread. One is to inherit the Thread class and the other is to implement the runnable interface. The two methods are essentially the same, but the design pattern is different.
Let's take a look at the first method: Inherit the Thread class.
Class demothread extends thread {
@ Override
Public void run (){
// Todo auto-generated method stub
Super. Run ();
System. Out. println ("demo thread running! ");
}
}
Public class mythread {
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Demothread = new demothread ();
Demothread. Start ();
}
}
Demothread inherits the Thread class, which means that demothread is now a Thread class and can be used as a thread to start (call the Thread class start () method ). then, the code in run () is executed.
Let's talk about the implementation of the runnable interface: the source code of runnable
Public interface runnable {
Public abstract void run ();
}
The implementation code is as follows:
Class demorunnable implements runnable {
@ Override
Public void run (){
// Todo auto-generated method stub
System. Out. println ("demo thread running! ");
}
}
Public class mythread {
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Demorunnable = new demorunnable ();
Thread thread = new thread (demorunnable );
Thread. Start ();
}
}
In fact, to implement a thread, you still need a thread object, and then pass in the constructor to implement the runnable interface class object, and call the START () method to enable the thread.
Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
2. Substantive and usage differences between the two methods
If we want to study the substantive differences between the two methods, we have to look at the source code of Java. Below I will briefly talk about the substantive differences between the two methods.
First, we need to know that after the start () method is called, the system will start to set the thread status to runnable (the thread status will be introduced soon ), then the run () method will be executed when the system time slice is the turn of this thread, so we need to compare
The difference between the two methods requires attention to the two points. The first point is the difference between their constructors, and the second point is the difference between the run methods.
First, let's look at the first kind of demothread = new demothread (). Because the subclass does not overwrite the constructor, this constructor actually calls the constructor of the parent class. check the source code of the thread constructor:
Public thread (){
Init (null, null, "thread-" + nextthreadnum (), 0 );
}
Thread thread = new thread (demorunnable );
Public thread (runnable target ){
Init (null, target, "thread-" + nextthreadnum (), 0 );
}
Then let's look at the init () method.
Private void Init (threadgroup g, runnable target, string name,
Long stacksize ){
If (name = NULL ){
Throw new nullpointerexception ("name cannot be null ");
}
Thread parent = currentthread ();
Securitymanager SECURITY = system. getsecuritymanager ();
If (G = NULL ){
/* Determine if it's an applet or not */
/* If there is a security manager, ask the security manager
What to do .*/
If (Security! = NULL ){
G = Security. getthreadgroup ();
}
/* If the security doesn' t have a strong opinion of the matter
Use the parent thread group .*/
If (G = NULL ){
G = parent. getthreadgroup ();
}
}
/* Checkaccess regardless of whether or not threadgroup is
Explicitly passed in .*/
G. checkaccess ();
/*
* Do we have the required permissions?
*/
If (Security! = NULL ){
If (isccloverridden (getclass ())){
Security. checkpermission (subclass_implementation_permission );
}
}
G. addunstarted ();
This. Group = g;
This. Daemon = parent. isdaemon ();
This. Priority = parent. getpriority ();
This. Name = Name. tochararray ();
If (SECURITY = NULL | isccloverridden (parent. getclass ()))
This. contextclassloader = parent. getcontextclassloader ();
Else
This. contextclassloader = parent. contextclassloader;
This. inheritedaccesscontrolcontext = accesscontroller. getcontext ();
This.tar get = target;
Setpriority (priority );
If (parent. inheritablethreadlocals! = NULL)
This. inheritablethreadlocals =
Threadlocal. createinheritedmap (parent. inheritablethreadlocals );
/* Stash the specified stack size in case the VM cares */
This. stacksize = stacksize;
/* Set thread ID */
Tid = nextthreadid ();
}
Let's take a look at the red part. In fact, the init () method called by the thread () constructor then runnable targetc passes it to the member variable of the thread. Next let's take a look at the run () method in thread.
If we use the first method to implement the thread, the target is empty when running run (), so it will directly execute the run () method rewritten by the subclass, the second type of target is actually the object that is passed in to implement the runnable interface, so the running () method is the object of the runnable interface class.
Now we are most concerned about the situation under which the two methods are used? In Java, classes are individually inherited. When a class has a parent class, we want to run it as a thread to implement the runnable interface, if there is no parent class, you can inherit the Thread class. however, I recommend that you try to use the method to implement the runnable interface. If your code needs to be restructured that day, it may not be necessary to abstract a parent class to the Thread class.
Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
3. thread status
Thread status:
When a new thread is generated and start () is called, the thread is in the runnable State. At this time, the system allocates time slices for each thread, if the time slice wheel reaches this thread, it will enter the running state. When the time slice passes, it will return to the runnable state again and again, until the thread stops running and enters the dead state. here there is a thread waiting status that needs to be specifically described, which is to synchronize the thread. as mentioned in the thread synchronization module below
Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
4. Synchronized Locking Mechanism
Now there are two tour groups at the same time to visit Tangyuan Park, but Tangyuan Park can only accommodate one tour group. At this time, the tour group needs to make an appointment with the person in charge of the Tangyuan scenic area, but there are more than one person in charge of Tangyuan Park, when a makes an appointment with the person in charge, B may also make an appointment with another person in charge. we can regard the AB tour group reservation as a thread and a line B. The Tangyuan scenic area can be regarded as an object, and the process of making an appointment with the person in charge can be used as a method for this object. then, line A and line B access the same method of the same object at the same time. however, sometimes we do not allow many threads to access the same resource. therefore, You need to lock resources to prevent concurrent access by multiple threads. each object is provided with a lock mechanism in Java to prevent multiple threads from simultaneously accessing the object's resources. we can use the synchronized keyword to lock member variables and member methods that are not allowed to be accessed by multiple threads in an object.
Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
5. synchronization between threads
Here is an example of two tour group AB. The relationship between the person in charge and tour group A is good. He hopes tour group A will visit Tangyuan first, so now there will be an appointment at the same time with tour group AB. However, the owner asks a to make an appointment. If B receives a call, the owner must wait for a to make an appointment.
In Java, the synchronous methods are wait () and Policy (). These two methods can be called only by locking the object (that is, adding the synchronized keyword.
Wait () mounts this thread
Y () notifies a mounted thread to execute
Finally, I am sending a demo of the previous example.
// Tour group
Class touringparta implements runnable {
Private principal;
Public touringparta (principal ){
This. Principal = principal;
}
@ Override
Public void run (){
// Todo auto-generated method stub
Principal. makeappointment (this );
}
}
// Tour group B
Class touringpartb implements runnable {
Private principal;
Public touringpartb (principal ){
This. Principal = principal;
}
@ Override
Public void run (){
// Todo auto-generated method stub
Principal. makeappointment (this );
}
}
// Owner
Class principal {
// Determine whether tour group A has made an appointment
Private Boolean isamakeappointment = false;
Public synchronized void makeappointment (runnable thread ){
If (thread instanceof touringpartb ){
If (! Isamakeappointment ){
Try {
Wait ();
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
System. Out. println ("tour group B has made an appointment! ");
}
Else {
System. Out. println ("tour group A's reservation is successful! ");
Isamakeappointment = true;
Notify ();
}
}
}
Public class journey {
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Principal principal = new principal ();
Touringparta = new touringparta (principal );
Touringpartb = new touringpartb (principal );
Thread T1 = new thread (touringparta );
Thread t2 = new thread (touringpartb );
T1.start ();
T2.start ();
}
}