00 start()
& run()
代码展示
import org.apache.log4j.Logger;
/**
* @ClassName StartAndRun
* @Description TODO
* @Author wenqing_liu
* @Date 2021/5/30 21:07
*/
public class StartAndRun {
private final Logger logger = Logger.getLogger(this.getClass());
public void runMethod() {
Thread t1 = new Thread("t1") {
@Override
public void run() {
logger.info("Thread Running...");
}
};
t1.run();
logger.info("Main Thread Running...");
}
public void startMethod() {
Thread t1 = new Thread("t1") {
@Override
public void run() {
logger.info("Thread Running...");
}
};
t1.start();
logger.info("Main Thread Running...");
}
}
测试代码
import org.junit.jupiter.api.Test;
/**
* @ClassName StartAndRunTest
* @Description TODO
* @Author wenqing_liu
* @Date 2021/5/30 21:10
*/
class StartAndRunTest {
@Test
void testStartMethod() {
StartAndRun sr = new StartAndRun();
sr.startMethod();
}
@Test
void testRunMethod() {
StartAndRun sr = new StartAndRun();
sr.runMethod();
}
}
01 run()
[Test worker] 21:19:56.369 INFO methods.StartAndRun:18 - Thread Running...
[Test worker] 21:19:56.373 INFO methods.StartAndRun:23 - Main Thread Running...
从上面的运行日志可以看出,日志打印的线程都是 [Test worker]
,可见方法调用还是同步的,
02 start()
[Test worker] 21:32:00.340 INFO methods.StartAndRun:35 - Main Thread Running...
[t1] 21:32:00.340 INFO methods.StartAndRun:30 - Thread Running...
运行测试方法 testStartMethod()
,调用 start()
方法后,日志打印的线程有 [Test worker], [t1]
, 方法的调用是异步的。
03 小结
- 直接调用
run()
方法,并没有启动新的线程 - 使用
start()
是启用新的线程,通过新的线程执行run()
中的方法