Multi-Thread [thread, Thread creation], multi-thread Thread

Source: Internet
Author: User

Multi-Thread [thread, Thread creation], multi-thread Thread

Main thread: The thread that executes the main method, which is called the main thread.

Single-threaded Program: Programs run from top to bottom from mani

The program starts to run from the main method. If the JVM runs the main method, it will find the operating system.
Open an execution path to the cpu. The cpu can use this path to execute the main method.
This path has a main thread.

Thread creation method 1 inherits the Thread class
Steps:
1. Create a subclass of the Thread class
2. Override the run method in the Thread class and set the Thread task.
3. Create a subclass object of the Thread class
4. Call the start method in the Thread class to open a new Thread and execute the run method.
The Java Virtual Machine calls the run method of the thread.
The result is that two threads run concurrently. The current thread (main thread) and the other thread (the thread that executes the run method ).
It is invalid to start a thread multiple times. In particular, the thread cannot be restarted after it has completed execution.

The printed results are random:
Enable two threads and select right for cpu
If you like it, you can execute it, so random results appear.

1 public class MyThread extends Thread {2/* 3*2. override the run method in the Thread class and set the Thread's Task 4 * what to do to enable this Thread 5 */6 @ Override 7 public void run () {8 for (int I = 0; I <50; I ++) {9 System. out. println ("run... "+ I); 10} 11} 12} 13 public static void main (String [] args) {14 // 3. create a subclass object of the Thread class 15 MyThread mt = new MyThread (); 16 // mt. run (); // does not enable the thread, or a single-threaded program 17 // 4. call the start method in the Thread class to open a new Thread and execute the run Method 18 mt. start (); 19 20 new MyThread (). start (); 21 22 for (int I = 0; I <50; I ++) {23 System. out. println ("main... "+ I); 24} 25}

Thread Name:
Main thread: "main"
Name of other threads enabled: "Thread-0", "Thread-1 "....

Get the thread name
1. The method getName In the Thread class
String getName () returns the name of the thread.
2. Obtain the currently executed Thread by using the static method in the Thread class.
Static Thread currentThread () returns a reference to the currently executed Thread object.
Set the thread Name:
1. setName (String name) method in the Thread class)
Void setName (String name) changes the thread name to be the same as the parameter name.
2. Add a parameter-based constructor to the subclass, call the parameter-based constructor of the parent Thread class, pass the Thread name, and let the parent class name the Thread (let the father name the son)
Thread (String name) allocates a new Thread object.


Thread creation method-implement the Runnable interface

Steps:
1. Create the Runnable interface implementation class
2. Override the run method in the Runnable interface and set the thread task
3. Create an implementation class object for the Runnable interface
4. Create a Thread Class Object and input the Runnable interface implementation class in the constructor.
Thread (Runnable target) allocates a new Thread object.
5. Call the start method in the Thread class and enable the Thread to execute the run method.


Benefits of Runnable
1. Avoid the failure to inherit other classes after the class inherits the Thread class (limitations of single inheritance)
2. Decoupling the set thread task from the enabled thread to improve scalability
The role of the Implementation class is to set the thread task
The role of the Thread class: To enable the Thread
Benefit: different implementation classes are passed, and the methods for implementing class rewriting are different. Different methods can be called.

Anonymous internal class usage of threads

Anonymous: No Name
Internal class: Class written inside other classes (member location: Member internal class, local location (method): Local internal class)

Formats of anonymous internal classes:
New parent class/interface (){
Override methods in the parent class/interface;
};

Multi-threaded parent class:
Thread
Runnable

1 new Thread () {2 // rewrite the run method and set Thread Task 3 @ Override4 public void run () {5 for (int I = 0; I <20; I ++) {6 System. out. println (Thread. currentThread (). getName () + ":" + I); 7} 8} 9}

The above code is a process of creating a subclass to override the parent class method.
Equivalent to: new MyThread (). start ();

The program encountered thread security issues: Repeated tickets and non-existent tickets were sold.

Solution:
Method 1: Synchronous Code blocks can be used.

Synchronized (Lock Object ){
Code that generates security issues;
Accessed the shared data code;
}

Note:
Make sure that multiple threads use the same lock object.
// Create a Lock Object (unique) on the member location)

1 Object obj = new Object (); 2 3 @ Override 4 public void run () {5 // Let the ticket repeatedly execute 6 while (true) {7 8 * synchronization code block 9 * the program will frequently judge the lock, obtain the lock, and release the lock, so the speed will be reduced by 10 11 synchronized (obj) {12 if (ticket> 0) {13 // to improve the probability of security issues, let the program Sleep 14 try {15 Thread. sleep (10); 16} catch (InterruptedException e) {17 e. printStackTrace (); 18} 19 // ticket sales ticket -- 20 System. out. println (Thread. currentThread (). getName () + "... sold "+ ticket -- +" tickets "); 21} 22} 23} 24}

The program encountered thread security issues: Repeated tickets and non-existent tickets were sold.

Solution:
Method 2: Synchronization Method

Procedure:
1. Extract the code that may cause security issues to a method.
2. Add a keyword synchronized to the method.
Modifier synchronized return value type method name (parameter ){
Code that may cause security issues;
Accessed the shared data code;
}

What is the lock object used by the synchronization method?
The Class Object new RunnableImpl () --> this

Static Synchronization Methods: What lock objects are used?
The class attribute (reflection) of the class object is used)
RunnableImpl. class

1 * @ Override 2 public void run () {3 // re-Execute 4 while (true) {5 payTicket2 (); 6} 7} 8 9 10 * static synchronization method 11 12 public static synchronized void payTicket2 () {13 synchronized (RunnableImpl. class) {14 if (ticket> 0) {15 // to improve the probability of security issues, let the program sleep 16 try {17 Thread. sleep (10); 18} catch (InterruptedException e) {19 e. printStackTrace (); 20} 21 // ticket selling ticket -- 22 System. out. println (Thread. currentThread (). getName () + "... sell "+ ticket -- +" tickets "); 23} 24} 25} 26 27 28 29 * extract a synchronization method 30 * shortcut key: alt + shift + m31 32 public ynchronized void payTicket1 () {33 synchronized (this) {34 // System. out. println (this); // cn. itcsat. demo10.RunnableImpl @ 6706435 if (ticket> 0) {36 // to improve the probability of security issues, let the program sleep 37 try {38 Thread. sleep (10); 39} catch (InterruptedException e) {40 e. printStackTrace (); 41} 42 // ticket selling ticket -- 43 System. out. println (Thread. currentThread (). getName () + "... sold "+ ticket -- +" tickets "); 44} 45} 46}

The program encountered thread security issues: Repeated tickets and non-existent tickets were sold.
*
* Solution:
* Method 3: Use the Lock interface.
*
* Java. util. concurrent. locks. Lock Interface
* Method:
* Void lock () is used to obtain the lock.
* Void unlock () releases the lock.
* Interface implementation class: ReentrantLock
*
* Steps:
* 1. Create a Lock interface implementation Class Object ReentrantLock in the member location
* 2. Call the lock method to obtain the lock before code that may cause thread security issues.
* 3. Call the unlock method to release the lock after code that may cause thread security issues.
*
* 1. Create a Lock interface implementation Class Object ReentrantLock in the member location
Lock l = new ReentrantLock ();

1 @ Override 2 public void run () {3 // re-Execute 4 while (true) {5 // 2. call the lock method to obtain the lock 6 l before code that may cause thread security issues. lock (); 7 if (ticket> 0) {8 // to improve the probability of security issues, let the program sleep 9 try {10 Thread. sleep (10); 11 // sell ticket -- 12 System. out. println (Thread. currentThread (). getName () + "... sell "+ ticket -- +" tickets "); 13} catch (InterruptedException e) {14 e. printStackTrace (); 15} finally {16 // 3. call the unlock method to release the lock 17 l after code that may cause thread security issues. unlock (); 18} 19} 20}

 

Related Article

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.