Multithreading refers to the technology of realizing the concurrent execution of multiple threads from software or hardware. Computers with multithreading capability can execute more than one thread at the same time because of hardware support, so as to improve the overall processing performance. Systems with this capability include Symmetric multiprocessor , multi-core processors and chip level multiprocessing or simultaneous multithreading processors. In a program In, these independently running program fragments are called“ thread ”(Thread), using its programming concept is called "multithreading" [1].
catalogue
A new understanding of multithreading
4. Thread common methods = = = sleep
5. The second method of creating multithreading
6. Create threads by anonymous internal classes
2.1 thread synchronization -- lock object
2.2 synchronization method -- solving thread safety problems
2.3} static method to solve thread safety problems
2.4} Lock to solve thread safety problems
Three thread wait wake-up case
A new understanding of multithreading
1. Multi thread creation
package com.itliuchao.six.xiancheng.ThreadDome2; //Define a subclass of Thread public class MyThread1 extends Thread{ @Override //Override the run method in the Thread class to set the Thread task public void run() { //Get thread name // String name = getName(); // System.out.println(name); // Thread t = Thread.currentThread(); // System.out.println(t); // String name = t.getName(); // System.out.println(name); // Chain programming System.out.println(Thread.currentThread().getName()); } } package com.itliuchao.six.xiancheng.ThreadDome2; /* Get thread Name: 1 Use the getName () method in the Thread class; 2 You can also get the current execution thread and use the method getName() in the thread to get the thread name Thread.currentThread() Returns a reference to the currently executing thread object Thread Name: main thread: main New thread: thread-0 thread-1 */ public class TestMyThread1 { public static void main(String[] args) { // Create a subclass object of Thread class MyThread1 myThread1 = new MyThread1(); //Call the start method to start a new thread and execute the run method myThread1.start(); // Get the name of the main thread by chain programming System.out.println(Thread.currentThread().getName()); } }
2 get thread name
package com.itliuchao.six.xiancheng.ThreadDome2; //Define a subclass of Thread public class MyThread1 extends Thread{ @Override //Override the run method in the Thread class to set the Thread task public void run() { //Get thread name // String name = getName(); // System.out.println(name); // Thread t = Thread.currentThread(); // System.out.println(t); // String name = t.getName(); // System.out.println(name); // Chain programming System.out.println(Thread.currentThread().getName()); } } package com.itliuchao.six.xiancheng.ThreadDome2; /* Get thread Name: 1 Use the getName () method in the Thread class; 2 You can also get the current execution thread and use the method getName() in the thread to get the thread name Thread.currentThread() Returns a reference to the currently executing thread object Thread Name: main thread: main New thread: thread-0 thread-1 */ public class TestMyThread1 { public static void main(String[] args) { // Create a subclass object of Thread class MyThread1 myThread1 = new MyThread1(); //Call the start method to start a new thread and execute the run method myThread1.start(); // Get the name of the main thread by chain programming System.out.println(Thread.currentThread().getName()); } }
3. Set thread name
package com.itliuchao.six.xiancheng.ThreadDome2; /* Set thread name (understand) Use the setName method in Theater */ public class TestMyThread2 { public static void main(String[] args) { //Turn on Multithreading MyThread2 myThread2 = new MyThread2(); myThread2.setName("Tractor"); myThread2.start(); //Turn on Multithreading new MyThread2("Harvester").start(); } } package com.itliuchao.six.xiancheng.ThreadDome2; public class MyThread2 extends Thread{ public MyThread2(){ } public MyThread2(String name){ super(name); //Pass the Thread name to the father and let the parent Thread give a name to the child Thread } @Override public void run() { //Get thread name System.out.println(Thread.currentThread().getName()); } }
The setPriority() and getPriority() methods of the Thread class are used to set and obtain the priority of the Thread respectively.
Each thread has a default priority. The default priority of the main thread is thread NORM_ PRIORITY.
The priority of threads is inherited. For example, if thread B is created in thread A, then thread B will have the same priority as thread A.
The JVM provides 10 Thread priorities, but it can't map well with common operating systems. If you want the program to be transplanted to each operating system, you should only use the Thread class with the following three static constants as the priority, so as to ensure that the same priority adopts the same scheduling method.
2. Thread sleep: thread Sleep (long millis) method to make the thread go to the blocking state. The millis parameter sets the sleep time in milliseconds. When the sleep is over, it changes to the Runnable state. sleep() platform has good portability.
3. Thread wait: the wait() method in the Object class causes the current thread to wait until other threads call the notify() method or notifyAll() method of the Object to wake up. These two wake-up methods are also methods in the Object class, and their behavior is equivalent to calling wait(0).
4. Thread: thread The yield () method pauses the thread object currently executing and gives the execution opportunity to threads with the same or higher priority.
5. Thread join: join() method, waiting for other threads to terminate. When the join() method of another thread is invoked in the current thread, the current thread is transferred to the blocking state until the end of the other process is completed, and the current thread is then changed from blocking to ready state.
6. Thread wakeup: the notify() method in the Object class wakes up a single thread waiting on this Object monitor. If all threads are waiting on this Object, one of them will be selected to wake up. The choice is arbitrary and occurs when a decision is made about the implementation. The thread waits on the Object's monitor by calling one of the wait methods. The awakened thread cannot continue executing until the current thread relinquishes the lock on this Object. The awakened thread will compete with all other threads actively synchronized on the Object in a conventional manner; For example, a awakened thread has no reliable privilege or disadvantage as the next thread to lock this Object. A similar method is notifyAll(), which wakes up all threads waiting on this Object monitor.
Note: the suspend() and resume() methods in Thread are in jdk1 5 has been abolished and will not be introduced. Because it tends to deadlock.
4. Thread common methods = = = sleep
package com.itliuchao.six.xiancheng.ThreadDome2; // Set the program sleep time to run public class Threadsleep { public static void main(String[] args) { // Analog stopwatch for (int i = 0; i <10 ; i++) { System.out.println(i); // Use the sleep method of Thread class to make the Thread sleep for one second try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
5. The second method of creating multithreading
package com.itliuchao.six.xiancheng.TheaterDome3; /* The second way to create a multithreaded program is to implement the Runnable interface Runnable Interfaces should be implemented by classes that intend to execute their instances through a thread. Class must define a parameterless method called run Thread(Runnable target) Assign a new Thread object. Thread(Runnable target, String name) Assign a new Thread object. Implementation steps: 1 Create an implementation class of Runnable interface 2 Override the run method of the Runnable interface in the implementation class to set the thread task 3 Create a Runnable interface implementation class object 4 Create a Thread class object and pass the Runnable interface to implement the class object in the constructor 5 Call the start method in the Thread class to start a new Thread and implement the run method */ public class MyRunnable { public static void main(String[] args) { // 3 create a Runnable interface implementation class object MyRunnableImpl myRunnable = new MyRunnableImpl(); // 4. Create a Thread class object and pass the Runnable interface to implement the class object in the constructor Thread thread = new Thread(myRunnable); // 5 call the start method in the Thread class to start a new Thread and implement the run method thread.start(); for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread().getName()+"---->"+i); } } } package com.itliuchao.six.xiancheng.TheaterDome3; //1. Create an implementation class of Runnable interface public class MyRunnableImpl implements Runnable{ //2 override the run method of the Runnable interface in the implementation class to set the thread task @Override public void run() { for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread().getName()+"---->"+i); } } }
6. Create threads by anonymous internal classes
package com.itliuchao.six.xiancheng; // Anonymous inner class implements thread creation /* Anonymous inner class function: simplify code The subclass inherits the parent class and overrides the parent class method to create the subclass object in one step The implementation class implementation interface is rewritten, and the method in the interface is created. The synthesis of the implementation class object is completed in one step The end product of an anonymous inner class is a subclass / implementation class object, and this class object Format: new Parent class / interface (){ Duplicate methods in parent class / interface }; */ public class Dome2 { public static void main(String[] args) { new Thread() { @Override public void run() { for (int i = 0; i <2 ; i++) { System.out.println(Thread.currentThread().getName()+"Boss Liu"); } } }.start(); // Thread interface Runnable //Runnable r =new MyRunnableImpl(); // Polymorphic writing Runnable runnable = new Runnable() { @Override public void run() { for (int i = 0; i <2 ; i++) { System.out.println(Thread.currentThread().getName()+"Liu Zong"); } } }; new Thread(runnable).start(); //Ways to simplify interfaces new Thread(new Runnable() { @Override //Override the run method to set the thread task public void run() { for (int i = 0; i <2 ; i++) { System.out.println(Thread.currentThread().getName()+"President Liu"); } } }).start(); } }
Two thread safety
2.1 thread synchronization -- lock object
package com.itliuchao.six.xiancheng.anlitickets1; /* The thread safety problem occurred in the simulated ticket buying case There are no duplicate tickets sold The first solution to the interface thread safety problem: use synchronous code blocks Format: synchronized(Lock object){ Thread safe code (code that accesses shared data) may appear } be careful: 1 Any object can be used through the lock object in the code 2 It must be ensured that the lock object used by multiple threads is the same 3 Lock object function: Lock the synchronous code block and only let another thread execute in the synchronous code block */ public class MyRunnableImpl implements Runnable { //1 define a multithreaded shared resource private int tickets =100; // Create a lock object Object obj =new Object(); @Override // Set thread task ticket public void run() { // Use an endless loop to repeat the ticket buying operation while (true){ synchronized (obj){ // First judge whether the ticket exists if (tickets>0){ // Improve the probability of security problems and let the program sleep try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"Selling" + tickets + "Ticket"); tickets--; } } } } } ----------------------------------- package com.itliuchao.six.xiancheng.anlitickets1; /* Simulated ticket buying case Create three lines and start selling shared tickets at the same time */ public class ThreadDome1 { public static void main(String[] args) { // Create Runnable interface implementation class object MyRunnableImpl mr = new MyRunnableImpl(); // Create the implementation class object of the transfer interface Runnable in the Theater class object construction method Thread thread = new Thread(mr); Thread thread1 = new Thread(mr); Thread thread2 = new Thread(mr); // Call start to start multithreading thread.start(); thread1.start(); thread2.start(); } }
2.2 synchronization method -- solving thread safety problems
package com.itliuchao.six.xiancheng.anlitickets2; /* A thread safety problem occurred in the ticket buying case Sold non-existent tickets and repeated votes The second way to solve thread safety problems is to use the synchronization method Use steps: 1 Extract the code that accesses the shared data into a method 2 Add the synchronized modifier on the method Format: defines the format of the method: Modifier synchronized return value type (parameter list){ Thread safe code (code that accesses shared data) may appear } */ public class MyRunnableImpl implements Runnable { //1 define a multithreaded shared resource private int tickets =100; @Override // Set thread task ticket public void run() { // Use an endless loop to repeat the ticket buying operation while (true) { //Call the following method method method(); } } /* Define a synchronization method Synchronous methods also lock the code inside the method Let only one thread execute The object locked by the synchronization method is the implementation class new MyRunnableImpl That is this */ public synchronized void method(){ // First judge whether the ticket exists if (tickets>0){ // Improve the probability of security problems and let the program sleep try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"Selling" + tickets + "Ticket"); tickets--; } } } package com.itliuchao.six.xiancheng.anlitickets2; /* Simulated ticket buying case Create three lines and start selling shared tickets at the same time */ public class ThreadDome1 { public static void main(String[] args) { // Create Runnable interface implementation class object MyRunnableImpl mr = new MyRunnableImpl(); // Create the implementation class object of the transfer interface Runnable in the Theater class object construction method Thread thread = new Thread(mr); Thread thread1 = new Thread(mr); Thread thread2 = new Thread(mr); // Call start to start multithreading thread.start(); thread1.start(); thread2.start(); } }
2.3} static method to solve thread safety problems
package com.itliuchao.six.xiancheng.anlitickets3; /* Ticket buying cases Static methods to solve thread safety problems (not focusing on understanding) */ public class MyRunnableImpl implements Runnable { //1 define a multithreaded shared resource private static int tickets =100; @Override // Set thread task ticket public void run() { // Use an endless loop to repeat the ticket buying operation while (true) { method(); } } public static synchronized void method(){ // First judge whether the ticket exists if (tickets>0){ // Improve the probability of security problems and let the program sleep try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"Selling" + tickets + "Ticket"); tickets--; } } } package com.itliuchao.six.xiancheng.anlitickets3; import com.itliuchao.six.xiancheng.anlitickets1.MyRunnableImpl; /* Simulated ticket buying case Create three lines and start selling shared tickets at the same time */ public class ThreadDome1 { public static void main(String[] args) { // Create Runnable interface implementation class object MyRunnableImpl mr = new MyRunnableImpl(); // Create the implementation class object of the transfer interface Runnable in the Theater class object construction method Thread thread = new Thread(mr); Thread thread1 = new Thread(mr); Thread thread2 = new Thread(mr); // Call start to start multithreading thread.start(); thread1.start(); thread2.start(); } }
2.4} Lock to solve thread safety problems
package com.itliuchao.six.xiancheng.anlitickets4; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /* A thread safety problem occurred in the ticket buying case Sold non-existent tickets and repeated votes The third way to solve thread safety problems is to use the Lock method*/ // The Lock implementation provides a wider range of Lock operations than can be obtained using synchronized methods and statements // Method of interface in Lock //void, lock() get lock //void unlock() releases the lock /* Use steps: 1 Create a ReentrantLock object at the member location 2 Call Lock in the Lock interface before getting code for security problems. 3 Call the method unLock release lock in the Lock interface after the code that may have security problems. */ public class MyRunnableImpl implements Runnable { //1 define a multithreaded shared resource private int tickets =100; // 1 create a ReentrantLock object at the member location Lock l= new ReentrantLock(); @Override // Set thread task ticket public void run() { // Use an endless loop to repeat the ticket buying operation /*while (true){ // 2 Call Lock in the Lock interface before getting code for security problems. l.lock(); // First judge whether the ticket exists if (tickets>0){ // Improve the probability of security problems and let the program sleep try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"Selling "+ tickets +" tickets "); tickets--; } // 3 Call the method unLock release lock in the Lock interface after the code that may have security problems. l.unlock(); }*/ // Use an endless loop to repeat the ticket buying operation while (true){ // 2 call the Lock in the Lock interface before getting code for security problems. l.lock(); // First judge whether the ticket exists if (tickets>0){ // Improve the probability of security problems and let the program sleep try { Thread.sleep(10); //Buying tickets System.out.println(Thread.currentThread().getName()+"Selling" + tickets + "Ticket"); tickets--; } catch (InterruptedException e) { e.printStackTrace(); }finally { // 3 call the method unLock release lock in the Lock interface after the code that may have security problems. l.unlock(); // The advantage of putting it in finally is that the lock will be released no matter what happens to the program } } } } } package com.itliuchao.six.xiancheng.anlitickets4; /* Simulated ticket buying case Create three lines and start selling shared tickets at the same time */ public class ThreadDome1 { public static void main(String[] args) { // Create Runnable interface implementation class object MyRunnableImpl mr = new MyRunnableImpl(); // Create the implementation class object of the transfer interface Runnable in the Theater class object construction method Thread thread = new Thread(mr); Thread thread1 = new Thread(mr); Thread thread2 = new Thread(mr); // Call start to start multithreading thread.start(); thread1.start(); thread2.start(); } }
Three thread wait wake-up case
package com.itliuchao.six.xiancheng.Dome5WaitandNofity; /* Wait for wake-up case: communication between threads Create a customer thread (consumer) to inform the boss of the number of packages, call the wait method, give up cpu execution and enter the WAITING state (wireless WAITING) The creation of a boss thread (producer) took five seconds to make a steamed stuffed buns to make a steamed stuffed bun, then called the notify method to wake customers to eat baozi. be careful: The customer and boss threads must be wrapped with synchronous code to ensure that there can only be one execution of waiting and wake-up Lock objects used synchronously must be unique Only lock objects can call the wait and notify methods */ public class Dome5WaitandNofity { public static void main(String[] args) { //Create a lock object to ensure uniqueness Object o = new Object(); //Create a customer thread new Thread(){ @Override public void run() { //Customers always want steamed stuffed buns while (true){ // The customer and boss threads must be wrapped with synchronous code to ensure that there can only be one execution of waiting and wake-up synchronized (o){ System.out.println("Boss, I want 18 steamed stuffed buns. Make them faster~~"); // Call the wait method to abort the cpu execution try { //Call the wait method to abandon cpu execution and enter the WAITING state (wireless WAITING) o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } // Code executed after wake-up System.out.println("I got the steamed stuffed bun l Brothers, eat"); System.out.println("==========================="); } } }.start(); //Create a thread boss (producer) new Thread(){ @Override public void run() { //The boss has been making steamed stuffed buns while (true){ // It takes five seconds to make steamed stuffed buns try { Thread.sleep(5000);//Make steamed stuffed buns for five seconds } catch (InterruptedException e) { e.printStackTrace(); } // Ensure that only one thread waiting for wake-up can execute, and the synchronization method needs to be used synchronized (o){ System.out.println("The boss began to make steamed stuffed buns and waited for five seconds. When the steamed stuffed buns are ready, please taste them!!!"); // After making the steamed stuffed bun, call notify method to wake customers to eat baozi. o.notify(); } } } }.start(); } }