Home > Java > Javagetting Started > body text

How to create a thread by inheriting the Thread class

王林
Release: 2020-06-23 18:03:26
forward
3741 people have browsed it

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()+":"+"输出的结果");
    }
     
}
Copy after login

(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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template