start表示启动线程,run只是执行线程体中的run方法并没有启动线程。
run方法
示例如下:
@Slf4j
public class TestStartAndRun {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
log.debug("T1线程执行了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.run();
log.debug("main线程执行了");
}
}
执行结果:
分析:
很明显假设t1线程已启动应该是先打印main线程先执行日志,因为T1线程睡了1s。所以并没有启动线程T1
start
将run改成start,示例如下:
package com.yzx.demo.test;
import lombok.extern.slf4j.Slf4j;
/**
* @auther: shuxing
* @date: 2022/5/10 21:29 周二
* @email: shuxing@dtstack.com
* @description:
*/
@Slf4j
public class TestStartAndRun {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
log.debug("T1线程执行了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
log.debug("main线程执行了");
}
}
执行结果:
分析:
很明显线程T1执行了,符合预期。