Home >Java >javaTutorial >How to start a new thread in java

How to start a new thread in java

王林
王林Original
2020-05-14 14:15:483263browse

How to start a new thread in java

We can start a new thread by inheriting the Thread class.

The steps are as follows:

1. Define a class A that inherits from the Java.lang.Thread class;

2. Override the run method in the Thread class in class A;

3. Write the operations that need to be performed in the run method: the code in the run method, the thread execution body;

4. Create the thread object in the main method (thread) and start the thread .

(1) Create a thread class object

A类 a = new A类();

(2) Call the start method of the thread object

a.start();//启动一个线程

(Video tutorial recommendation: java video)

Note: Never call the run method. If you call the run method, it is like calling a method on an object. There will still be only one thread and no new thread will be started. A thread can only be started once.

The specific examples are as follows:

//1):定义一个类A继承于java.lang.Thread类.  
class MusicThread extends Thread{  
    //2):在A类中覆盖Thread类中的run方法.  
    public void run() {  
        //3):在run方法中编写需要执行的操作  
        for(int i = 0; i < 50; i ++){  
            System.out.println("播放音乐"+i);  
        }  
    }  
}  
  
public class ExtendsThreadDemo {  
    public static void main(String[] args) {  
          
        for(int j = 0; j < 50; j ++){  
            System.out.println("运行游戏"+j);  
            if(j == 10){  
                //4):在main方法(线程)中,创建线程对象,并启动线程.  
                MusicThread music = new MusicThread();  
                music.start();  
            }  
        }  
    }  
  
}

Recommended tutorial: java entry program

The above is the detailed content of How to start a new thread in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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