介绍线程创建的两种基本的方法:继承Thread类和实现Runnable接口
1. 继承Thread类
- 自定义类继承Thread类,重写 run() 方法
import org.slf4j.LoggerFactory;
/**
* @author: yt
* @date: 2021/4/12 22:09
* @description: 创建Thread类继承Thread
*/
public class MyThread extends Thread{
private static final Logger log = LoggerFactory.getLogger(MyThread.class);
MyThread(String name){
super(name);
}
@Override
public void run() {
log.debug("thread running...");
}
}
public class Test1 {
private static final Logger log = LoggerFactory.getLogger(Test1.class);
public static void main(String[] args) {
// myThread 是线程名称
MyThread myThread = new MyThread("myThread");
// 调用start方法启动线程,程序会执行run()方法
myThread.start();
}
}
或者直接用匿名内部类实现
public class Test1 {
private static final Logger log = LoggerFactory.getLogger(Test1.class);
public static void main(String[] args) {
Thread myThread = new Thread("myThread") {
@Override
public void run() {
log.debug("thread running...");
}
};
myThread.start();
}
}
调用start() 方法启动线程,线程启动后会执行run()方法。
运行结果:
2021-04-12 22:26:27 [myThread] - thread running...
2.实现Runnable接口
实现Runnable接口,重写run()方法,然后将Runnable实例丢给Thread类实例化,即可新建一个新的线程,一样是调用线程对象的start()的方法来启动线程。
java8 以后可以使用Lambda 表达式来 创建Runnable实例
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author: yt
* @date: 2021/4/12 22:01
* @description:
*/
public class Test1 {
private static final Logger log = LoggerFactory.getLogger(Test1.class);
public static void main(String[] args) {
// 方法一:使用匿名内部类实现接口
Runnable runnable1 = new Runnable() {
@Override
public void run() {
log.debug("runnable1 running...");
}
};
// Thread实例化,第一个参数为Runnable,第二个参数为线程名称
Thread thread1 = new Thread(runnable1,"runnable1");
// 启动线程
thread1.start();
// 方法二:使用Lambda表达式实现接口
Runnable runnable2 = ()->{log.debug("runnable2 running...");};
Thread thread2 = new Thread(runnable2,"runnable2");
thread2.start();
log.debug("main 方法");
}
}
运行结果:
2021-04-12 22:36:32 [runnable1] - runnable1 running...
2021-04-12 22:36:32 [main] - main 方法
2021-04-12 22:36:32 [runnable2] - runnable2 running...
标签:Runnable,log,Thread,编程,并发,myThread,线程,public
From: https://www.cnblogs.com/Aeons/p/18375493