Main thread: The threads that execute the main method are called the main threading
Single-threaded program: programs run from top to bottom starting from Mani
The program runs from the main method, and the JVM runs the main method, looking for the operating system
Opens a path to the CPU that the CPU can use to execute the Main method
This path has a name called Main (main) thread
Create thread mode one inherits the thread class
Implementation steps:
1. Create a subclass of the thread class
2. Override the Run method in the thread class to set the task for the thread
3. Create a subclass object for the thread class
4. Call the Start method in the thread class to open a new thread, execute the Run method
Causes the thread to start executing, and the Java virtual machine calls the thread's Run method.
The result is two threads running concurrently, when the thread (main thread) and another thread (the one executing the Run method).
It is illegal to start a thread multiple times. This is especially the time when the thread has finished executing and cannot be restarted.
The results of the printing appear random:
Turn on two threads, select right for CPU
Who you like, who you execute, so there's a random result.
1 Public classMyThreadextendsthread{2 /*3 * 2. Override the Run method in the thread class to set the task for the thread4 * What does it take to open this thread?5 */6 @Override7 Public voidrun () {8 for(inti = 0; I < 50; i++) {9System.out.println ("Run ..." +i);Ten } One } A } - Public Static voidMain (string[] args) { - //3. Create a subclass object for the thread class theMyThread MT =NewMyThread (); - //Mt.run ();//does not open threads, or single-threaded - //4. Call the Start method in the thread class to open a new thread, execute the Run method - Mt.start (); + - NewMyThread (). Start (); + A for(inti = 0; I < 50; i++) { atSystem.out.println ("Main ..." +i); - } -}
Name of the thread:
Main thread: "Main"
The name of the other thread that is turned on: "Thread-0", "Thread-1" ....
Gets the name of the thread
Methods in the 1.Thread class GetName
String GetName () returns the name of the thread.
Static methods in the 2.Thread class to get the currently executing thread
The static thread CurrentThread () returns a reference to the currently executing thread object.
Set the name of the thread:
Method SetName (String name) in the 1.Thread class
void SetName (String name) changes the name of the thread so that it is the same as the parameter name.
2. Subclass add a parameter construct, call the parameter construction method of the parent class thread class, pass the name of the thread, let the parent class give the thread a name (let the Father name the son)
The thread (String name) assigns a new thread object.
Create thread mode-Implement Runnable interface
Implementation steps:
1. Creating an implementation class for the Runnable interface
2. Override the Run method in the Runnable interface to set the thread task
3. Creating an implementation class object for the Runnable interface
4. Create the Thread class object and construct the implementation class for the incoming runnable interface in the method
Thread (Runnable target) assigns a new thread object.
5. Call method start in the thread class to open thread execution Run method
Benefits of achieving Runnable
1. After the class inherits the thread class, the other classes cannot be inherited (limitations of single inheritance)
2. Decoupling the setup thread task, and the open thread, enhances scalability
The purpose of the implementation class is to set the thread task
Role of the thread class: Opening threads
Benefits: Different implementation classes are passed, different methods are implemented to implement class overrides, and various methods can be called
Anonymous internal classes for threads are used
Anonymous: No Name
Inner classes: Classes that are written inside other classes (member positions: Members inner classes, local locations (methods): Local inner classes)
The format of the anonymous inner class:
New parent class/interface () {
Overrides the method in the parent class/interface;
};
Multi-threaded Parent class:
Thread
Runnable
1 NewThread () {2 //override the Run method to set the thread task3 @Override4 Public voidrun () {5 for(inti = 0; I < 20; i++) {6System.out.println (Thread.CurrentThread (). GetName () + ":" +i);7 }8 }9}
The above heap of code is a procedure for creating subclasses to override parent class methods
Equivalent: New MyThread (). Start ();
The program has a thread-safety issue: Sell duplicate tickets and non-existent tickets
Solution:
The first way: You can use a synchronous block of code
Synchronized (lock object) {
Code that generates security issues;
The code that accesses the shared data;
}
Attention:
You must ensure that multiple threads are using the same lock object
Create a lock object on the member location (guaranteed unique)
1Object obj =NewObject ();2 3 @Override4 Public voidrun () {5 //let the ticket be executed repeatedly6 while(true){7 8*Synchronizing code blocks9*The program will frequently judge the lock, get the lock, release the lock, so it will slow downTen One synchronized(obj) { A if(ticket>0){ - //in order to improve the probability of security problems, let the program sleep - Try { theThread.Sleep (10); -}Catch(interruptedexception e) { - e.printstacktrace (); - } + //Sell Tickets ticket-- -System.out.println (Thread.CurrentThread (). GetName () + "... Sell the "+ticket--+" ticket); + } A } at } -}
The program has a thread-safety issue: Sell duplicate tickets and non-existent tickets
Solution:
Second way: Synchronization method
Steps to use:
1. Extract code that may have security problems into one method
2. Add a keyword to the method synchronized
Modifier synchronized return value type method name (parameter) {
Code that may present a security issue;
The code that accesses the shared data;
}
What is the lock object used by the synchronization method?
This is the object of this class, New Runnableimpl (), called this
Static synchronization method, what is the lock object used?
The class attribute (reflection) of the object is used
Runnableimpl.class
1*@Override2 Public voidrun () {3 //let the ticket be executed repeatedly4 while(true){5 PayTicket2 ();6 }7 }8 9 Ten*a static synchronization method One A Public Static synchronized voidPayTicket2 () { - synchronized(Runnableimpl.class) { - if(ticket>0){ the //in order to improve the probability of security problems, let the program sleep - Try { -Thread.Sleep (10); -}Catch(interruptedexception e) { + e.printstacktrace (); - } + //Sell Tickets ticket-- ASystem.out.println (Thread.CurrentThread (). GetName () + "... Sell the "+ticket--+" ticket); at } - } - } - - - in*Pull out a synchronization method -* Shortcut key: alt+shift+m to + PublicYnchronizedvoidPayTicket1 () { - synchronized( This) { the //System.out.println (this);//[email protected] * if(ticket>0){ $ //in order to improve the probability of security problems, let the program sleepPanax Notoginseng Try { -Thread.Sleep (10); the}Catch(interruptedexception e) { + e.printstacktrace (); A } the //Sell Tickets ticket-- +System.out.println (Thread.CurrentThread (). GetName () + "... Sell the "+ticket--+" ticket); - } $ } $}
The program has a thread-safety issue: Sell duplicate tickets and non-existent tickets
*
* Solution:
* Third Way: Using the Lock interface, the JDK1.5 appears after the
*
* Java.util.concurrent.locks.Lock Interface
Method
* void Lock () gets the lock.
* void Unlock () release lock.
* Interface Implementation class: Reentrantlock
*
* Implementation steps:
* 1. Create an implementation class object for the lock interface in the member location Reentrantlock
* 2. Call the lock method to get the lock before the code that is likely to have a thread safety problem
* 3. Call the Unlock method to release the lock after code that may have a thread safety problem
*
* * Create an implementation class object in the member location for a lock interface Reentrantlock
Lock L = new Reentrantlock ();
1 @Override2 Public voidrun () {3 //let the ticket be executed repeatedly4 while(true){5 //2. Call the lock method to get the lock before the code that is likely to have a thread safety problem6 L.lock ();7 if(ticket>0){8 //in order to improve the probability of security problems, let the program sleep9 Try {TenThread.Sleep (10); One //Sell Tickets ticket-- ASystem.out.println (Thread.CurrentThread (). GetName () + "... Sell the "+ticket--+" ticket); -}Catch(interruptedexception e) { - e.printstacktrace (); the}finally { - //3. Call the Unlock method to release the lock after code that may have a thread safety issue - L.unlock (); - } + } -}
Multithreading "Thread, Thread creation"