Threads
Multithreading is a program in which multiple threads are executing concurrently.
How the CPU works under multi-threading
In fact, theCPU ( central processing Unit ) uses preemptive scheduling mode to switch between multiple threads at high speed . For one core of the CPU , at some point, only one thread can be executed, and the CPU switches between multiple threads faster than we feel, and looks like it is running at the same time.
In fact, multi-thread programs can not improve the speed of the program, but it can improve the efficiency of the program, so that the CPU utilization is higher.
first, create a threadMethod 1: Inherit the thread class, overriding the Run method
public class Subthread extends thread{public subthread () { super ("x5456"); Modify the thread name by constructing the method } public void Run () {for (int i=0;i<100;i++) { System.out.println (super.getname () + i);}} }
Call:
public static void Main (string[] args) { //Create an object that just inherits the subclass of the thread class Subthread st = new Subthread (); Through the SetName method, modify the thread name st.setname ("x54256"); Call the object's Start method, which automatically executes our rewritten Run method St.start (); for (int i=0;i<100;i++) { System.out.println (Thread.CurrentThread (). GetName () +i); Gets the object of the current thread, calling the GetName () method }}
Method 2: Implement Interface runnable, override the Run method
public class Subrunnable implements runnable{public void Run () {for (int i=0;i<100;i++) { try { // Call the Thread class's sleep method, Hibernate 50ms, because the parent interface has no throws exception, so we can only use Try...catch thread.sleep; } catch ( Interruptedexception e) { e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + "..." +i);}}
Call:
public static void Main (string[] args) { //Create an object for the class that implements the Runnable interface subrunnable sr = new subrunnable (); Create the thread class object thread t = new Thread (SR); Start thread t.start (); for (int i=0;i<100;i++) { System.out.println (Thread.CurrentThread (). GetName () + "..." +i);} }
Method 3: Use anonymous inner classes to implement multi-threaded procedures
Prerequisites for Anonymous internal classes: Inheritance or interface implementations
How to use:
New parent class or interface () {
overriding abstract methods
}
public static void Main (string[] args) {//Inheritance way XXX extends thread{public void run () {}}new Thread () {public void run () { SYSTEM.OUT.PRINTLN ("!!!");}}. Start ();//Implement Interface mode XXX implements runnable{public void run () {}}runnable r = new Runnable () {public void run () {System.ou T.println ("# # #");}; New Thread (R). Start ();//================== or =====================new Thread (new Runnable () {public void run () { System.out.println ("@@@");}}). Start ();}
Benefits of implementing interfaces:
Cohesion Poly, low coupling: The module can do things on their own, the relationship between the modules as small as possible
The second way to implement the Runnable interface avoids the limitation of single inheritance, so it is more commonly used. Implement the Runnable interface in a way that is more consistent with object-oriented, the thread is divided into two parts, a part of the thread object, a part of the thread task. Inheriting the thread class, the threading object and the thread task are coupled together. Once the subclass object of the thread class is created, it is both a threaded object and a thread-path task. Implement the runnable interface, separate the thread tasks into objects, and the type is the runnable interface type. The Runnable interface decouples thread objects and thread tasks.
multi-threaded memory plots:Thread of Life:
second, thread pool
The thread pool, in fact, is a container that accommodates multiple threads, where threads can be reused, eliminating the need to create thread objects frequently and consuming excessive resources without having to create threads repeatedly.
In Java , it is quite expensive to create a new thread if each request arrives. In practice, the time spent creating and destroying threads and the amount of system resources consumed are quite large, and may even be more than the time and resources required to process actual user requests. In addition to the overhead of creating and destroying threads, the active thread also consumes system resources. If you create too many threads in a single JVM , you may cause your system to be running out of resources due to excessive memory consumption or "over-switching". To prevent resource shortages, there are ways to limit the number of requests processed at any given moment, minimizing the number of threads that are created and destroyed, especially if some of the resources are expensive to create and destroy, and use existing objects to service them as much as possible.
Thread pooling is primarily used to address thread life-cycle overhead and resource-poor issues. By reusing threads for multiple tasks, the overhead of thread creation is distributed across multiple tasks, and the delay caused by thread creation is eliminated because the thread already exists when the request arrives. In this way, you can immediately service the request and use the application to respond faster. In addition, the lack of resources can be prevented by adjusting the number of threads in the thread appropriately.
Method 1: Use the thread pool mode --runnable interface
public static void Main (string[] args) { //Call a static method of the factory class, create a thread pool object (Implementation class for the Executorservice interface) //Return to the thread pool object, which is the returned interface Executorservice es = Executors.newfixedthreadpool (2); The pool has 2 threads //Call Interface implementation class object ES in the method submit thread task //Will runnable interface implementation class object, pass es.submit (new subrunnable ()); Es.submit (New subrunnable ()); Es.submit (New subrunnable ()); Es.submit (New subrunnable ());}
Implementation of the Runnable interface
public class Threadpoolrunnable implements Runnable {public void run () {System.out.println (Thread.CurrentThread (). GetName () + "thread submission task");}}
Method 2: Use the thread pool mode -callable interface
The previous implementation method, the thread runs out of no return value, and cannot throw an exception.
callable interface : Similar to the Runnable interface function, used to specify a thread's task. The call () method, which returns the result of the completion of the thread task , throws an exception.
public static void Main (string[] args) throws Executionexception, interruptedexception { Executorservice es = Executo Rs.newfixedthreadpool (2); Methods for submitting thread tasks The Submit method returns the implementation class for the future interface future<integer> f = es.submit (new subcallable ()); Gets the return value of Integer i = F.get (); System.out.println (i);}
Implementation of the Callable interface
public class Subcallable implements callable<integer>{ @Override public Integer call () { return 123; }}
using threads to implement asynchronous computations
private int a;//is passed through the constructor method public getsumcallable (int a) {this.a=a;} Public Integer call () {int sum = 0, for (int i = 1; i <=a; i++) {sum = sum + i;} return sum;}
Threadpooldemo.java
/* * Use multithreading technology, SUM * Two threads, 1 threads compute 1+100, another thread computes 1+200 and * Multithreaded asynchronous computations */public class ThreadPoolDemo {public static void main (String [] args) throws Exception {Executorservice es = Executors.newfixedthreadpool (2); Future<integer> F1 =es.submit (new getsumcallable (100)); future<integer> F2 =es.submit (new Getsumcallable (200)); System.out.println (F1.get ()); System.out.println (F2.get ()); Es.shutdown ();}}
java--threading creation, thread pool