Preface
A thread is a sequential control flow within a program. CPU actually executes only one at a point in time. It's just that we split the cup into multiple time slices, and because of the speed, we look like multiple threads. Just like your time is divided into several pieces, the overall situation will look regular and the efficiency will be high, let alone cup.
Thread creation and startup:
(1) Define a subclass of Thread class and override the run() method of the class. The method of run() method represents the task that the thread needs to complete. Therefore, run() method is called the thread execution body
(2) Create an instance of Thread subclass, that is, create a thread object
(3) Call start() method of the thread object to start the thread
source code:
// Create thread class by inheriting the Thread class public class FirstThread extends Thread{private int i;//Rewrite the run() method. The method body of the run() method is the thread execution body public void run(){for(;i<100;i++){//When the thread class inherits the Thread class, use this directly to get the current data //The getName() of the Thread object returns the name of the current thread // Therefore, you can directly call the getName() method to return the name of the current thread System.out.println(getName()+""+i);}} public static void main(String[] args){ for(int i=0;i<100;i++){//Calling Thread's currentThread() method to get the current thread System.out.println(Thread.currentThread().getName() +""+i);if(i==20){//Creating and starting the first thread new FirstThread().start();//Creating and starting the second thread new FirstThread().start();}}}}}}Running interface:
Summarize
The above is all about this article, I hope it will be helpful to everyone's study and work. If you have any questions, please leave a message to discuss.