Home  >  Article  >  Java  >  How to create a thread by inheriting the Thread class

How to create a thread by inheriting the Thread class

王林
王林forward
2020-06-23 18:03:263685browse

How to create a thread by inheriting the Thread class

The steps to inherit the Thread class to create a thread are:

(Recommended tutorial: Getting Started with Java Development)

(1) Create a class that inherits the Thread class, rewrite the run() method, and write the task code to be completed into the run() method;

(2) Create an object of a subclass of the Thread class;

(3) Call the start() method of the object. The start() method means to start the thread first and then call the run() method;

Code example:

public class Thread1 {
     
    public static void main(String[] args) {
         
        Thread.currentThread().setName("主线程");
        System.out.println(Thread.currentThread().getName()+":"+"输出的结果");
        //创建一个新线程
        ThreadDemo1 thread1 = new ThreadDemo1();
        //为线程设置名称
        thread1.setName("线程一");
        //开启线程
        thread1.start();
    }
}
 
class ThreadDemo1 extends Thread{
     
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+":"+"输出的结果");
    }
     
}

(Video tutorial Recommended: java video tutorial)

The above is the detailed content of How to create a thread by inheriting the Thread class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete