[Java multithreading] Two methods of creating and using custom threads

[Java multithreading] Two common methods for creating and using custom threads

Summarize two common methods of creating and using custom threads in Java.
Here by implementing a most simple of custom multi-threaded categories : Morty class , and contains only main function of the test class: ThreadTest class to show results.

Method 1: Inherit the Thread class

The simplest and most direct method is to inherit the Thread class. It is enough to implement the run function required by the Thread class .

Advantages: clear and straightforward.
Disadvantages: Only one class can be inherited in Java, and the usage scenarios are limited.

class Morty extends Thread {
    
    
	// 定义成员和构造器..
	
	// 定义run函数
	public void run() {
    
    
		System.out.println("我是一个Thread类,平行空间里无数Morty中的一个");
	}

	// 定义各种方法..
}

public class ThreadTest {
    
    
	public static void main(String[] args) {
    
    
		Morty morty0 = new Morty();	// 初始化线程(本例中使用默认构造器)
		morty0.start();				// 启动线程
	}
}

operation result:

Thread running results

Method 2: Implement Runnable interface

Advantages: A class can implement multiple interfaces, which is widely applicable.
Disadvantages: It is not as simple and direct as directly inheriting the Thread class (but it feels similar to use).

class Morty implements Runnable {
    
    
    // 定义成员和构造器..

    // 定义run函数
    public void run() {
    
    
        System.out.println("我是一个Thread类,平行空间里无数Morty中的一个");
    }

    // 定义各种方法..
}

public class ThreadTest {
    
    
    public static void main(String[] args) {
    
    
        Morty mortyTemp = new Morty();	           // 初始化线程(本例中使用默认构造器)
        Thread morty137 = new Thread(mortyTemp);   // 初始化线程

//		Thread morty137 = new Thread(new Morty()); // 也可以这样简写

        morty137.start();				           // 启动线程
    }
}

operation result:

Runnable mode operation result



(End. Recommended reading: Multithreading in Java )

Guess you like

Origin blog.csdn.net/weixin_39591031/article/details/110090304