SecondThread sec = new SecondThread("zs");
SecondThread thr = new SecondThread("lsii");
//Set sec and thr threads as daemon threads
sec.setDaemon(true);
thr.setDaemon(true);
//Start
sec.start();
thr.start();
//When it is found that sec and thr are daemon threads, it will be interrupted
* **Interrupt thread**: `public void interrupt()`: This method can be used to let one thread control another thread (conditional: blocked)**termination**Run of another thread > 1\. If the thread is calling Object Class wait(),wait(long) or wait(long, int) Method, or of this class join(),join(long),join(long, int),sleep(long) or sleep(long, int) When the blocking method is blocked, it will also receive a InterruptedException > 2\. There is no need to interrupt an inactive thread. > Interrupting a thread that is not blocked has no other effect ```java public class Test { public static void main(String[] args) { FiveThread fiveThread = new FiveThread(); fiveThread.start(); //In the main thread, terminate the fiveThread to sleep fiveThread.interrupt(); } } // After sleeping for 5 seconds, let the thread output a sentence class FiveThread extends Thread{ @Override public void run() { try { //If you apply for a lot of system resources TimeUnit.SECONDS.sleep(5); System.out.println("FiveThread I wake up"); } catch (InterruptedException e) { e.printStackTrace(); //Meaning of exception: even if my thread is terminated abnormally, I can ensure the normal release of resources } } } //java.lang.InterruptedException: sleep interrupted will be thrown
4. Operation principle of Java program
- The Java command will start the JVM, that is, a process is started. The process will start a main thread, and then the main thread will call a class Main method, so the main method runs in the main thread
- After the jvm is started, there must be an execution path (thread) from the main method to the end of the main method. This thread is called the main thread in Java.
- When the main thread of the program executes, if a loop is encountered and the program stays at the specified position for too long, the following program cannot be executed immediately. It needs to wait for the loop to be executed after the loop is completed
- Method runs in the thread in which it is called
- A JVM is a multithreaded program, and each Java process is assigned a JVM instance
public class ThreadDemo { public static void main(String[] args) { //Use the garbage collector to prove while(true) { //Although we have been creating array objects in heap space, // But it never ran out of heap space because of the garbage collector, // In another thread, help us recycle garbage, so we won't run out of heap memory // This proves that the jvm is threaded int[] ints = new int[1024]; ints = null; } } }
2, Thread class
1. General
- Thread is the execution thread in the program. The Java virtual machine allows applications to run multiple execution threads concurrently
- Not an abstract class
2. Construction method
- Thread(): assign a new thread object
- Thread(String name): assign a new thread object and take the specified name as its thread name
3. Common methods
- void start(): start the thread to execute, and the Java virtual machine calls the run method of the thread
- void run(): the operation to be executed by the thread,
- static void sleep(long millis): hibernates the currently executing thread and suspends execution within a specified millisecond
- static Thread currentThread(): returns the reference Thread.currentThread() of the thread object currently executing
4. Two methods to create a new execution thread
- Declare a class as Thread Subclass of. This subclass should override the of the thread class run method. Create the object and start the thread. The run method is equivalent to the main method of other threads.
- Declare an implementation Runnable Class of the interface. The class then implements run method. Then create a subclass object of runnable, pass it into the construction method of a thread, and start the thread.
Although there are two ways to implement a Thread, objectively speaking, the Thread itself only represents an independent execution path. The specific content of execution is actually the task itself, which is not related to the implementation of the execution path itself; We developers just want to run a task in an independent execution path (Thread class object, that is, a Thread)
3, Create Thread: inherit Thread class
-
To create a thread
-
Define a class that inherits Thread
-
Override run method
-
To create a subclass object is to create a thread object
-
Call the start method, start the thread and let the thread execute, and tell the jvm to call the run method
Thread object call run method Do not open thread. Only objects call methods.
Thread object call start Start the thread and let the jvm call the run method to execute in the open thread
//Test class public class Test { public static void main(String[] args) { //Create custom thread object MyThread mt = new MyThread("New thread!"); //Error starting thread, this is just a normal method call //firstThread.run(); //Open new thread mt.start(); //Starting a thread again will throw an exception, IllegalThreadStateException //Because a thread object can only be started once, // If the same thread object is started multiple times, an exception will be thrown //firstThread.start(); //Only one new object can be created new MyThread("Second thread!").start(); //Gets the name of the main thread System.out.println(Thread.currentThread().getName()+": Main thread!"); } } //Custom thread class MyThread extends Thread { //Defines the constructor for the specified thread name public MyThread(String name) { //Call the constructor of the String parameter of the parent class to specify the name of the thread super(name); } //Rewrite the run method to complete the logic executed by the thread @Override public void run() { //Get the name of the thread getName() System.out.println(getName() + ": Executing!"); } }
4, Create thread: implement Runnable interface
1. Construction method of runnable interface
- Thread(Runnable target): assign a new thread object so that the target is its running object
- Thread(Runnable target,String name) : Assign a new thread object to take target as its running object; And use the specified name as its name
2. Steps to create a thread
- Define class implementation Runnable Interface.
- Override in interface run method
- To create a Thread class object
- Pass the subclass object of the Runnable interface as a parameter to Thread class Construction method of.
- Calling the Thread class start() Start the Thread.
Constructor of Thread class:
one Thread(): assign a new thread object
two Thread(String name): assign a new thread object and take the specified name as its thread name
//Test class public class Test { public static void main(String[] args) { //Create a subclass object that implements the Runnable interface MyRunnable myrunnable = new MyRunnable(); //Create a Thread instance and pass the Runnable instance in the Thread construction method //Runnable represents the task running on the Thread Thread thread = new Thread(myrunnable); //Open thread thread.start(); for (int i = 0; i < 10; i++) { System.out.println("main Thread: executing!"+i); } } } //Custom thread execution task class class MyRunnable implements Runnable{ //Define the run method logic to be executed by the thread //run method, cannot throw compile time exception //run method, no parameters, no return value @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("My thread: executing!"+i); } } }
3. Principle of realizing Runnable interface
Why do you need to specify a class to implement the Runnable interface? What is the difference between inheriting the Thread class and implementing the Runnable interface?
Only objects that create Thread classes can create threads. The Thread task has been encapsulated in the run method of the Runnable interface, and the run method belongs to the subclass object of the Runnable interface. Therefore, this subclass object is passed to the Thread constructor as a parameter, so that the task of the Thread to be run can be specified when the Thread object is created
4. Comparison of the two methods
last
That's all I want to share with you this time
**[CodeChina open source project: [analysis of Java interview questions of first-line large manufacturers + core summary learning notes + latest explanation Video]](
)**
Finally, share a big gift package (learning notes) of the ultimate hand tearing architecture: distributed + microservices + open source framework + performance optimization
Therefore, this subclass object is passed as a parameter to the Thread constructor, so that the task of the Thread to be run can be specified when the Thread object is created
4. Comparison of the two methods
last
That's all I want to share with you this time
**[CodeChina open source project: [analysis of Java interview questions of first-line large manufacturers + core summary learning notes + latest explanation Video]](
)**
Finally, share a big gift package (learning notes) of the ultimate hand tearing architecture: distributed + microservices + open source framework + performance optimization