00 start() & run() 代码展示

  1. import org.apache.log4j.Logger;
  2. /**
  3. * @ClassName StartAndRun
  4. * @Description TODO
  5. * @Author wenqing_liu
  6. * @Date 2021/5/30 21:07
  7. */
  8. public class StartAndRun {
  9. private final Logger logger = Logger.getLogger(this.getClass());
  10. public void runMethod() {
  11. Thread t1 = new Thread("t1") {
  12. @Override
  13. public void run() {
  14. logger.info("Thread Running...");
  15. }
  16. };
  17. t1.run();
  18. logger.info("Main Thread Running...");
  19. }
  20. public void startMethod() {
  21. Thread t1 = new Thread("t1") {
  22. @Override
  23. public void run() {
  24. logger.info("Thread Running...");
  25. }
  26. };
  27. t1.start();
  28. logger.info("Main Thread Running...");
  29. }
  30. }

测试代码

  1. import org.junit.jupiter.api.Test;
  2. /**
  3. * @ClassName StartAndRunTest
  4. * @Description TODO
  5. * @Author wenqing_liu
  6. * @Date 2021/5/30 21:10
  7. */
  8. class StartAndRunTest {
  9. @Test
  10. void testStartMethod() {
  11. StartAndRun sr = new StartAndRun();
  12. sr.startMethod();
  13. }
  14. @Test
  15. void testRunMethod() {
  16. StartAndRun sr = new StartAndRun();
  17. sr.runMethod();
  18. }
  19. }

01 run()

  1. [Test worker] 21:19:56.369 INFO methods.StartAndRun:18 - Thread Running...
  2. [Test worker] 21:19:56.373 INFO methods.StartAndRun:23 - Main Thread Running...

从上面的运行日志可以看出,日志打印的线程都是 [Test worker] ,可见方法调用还是同步的,

02 start()

  1. [Test worker] 21:32:00.340 INFO methods.StartAndRun:35 - Main Thread Running...
  2. [t1] 21:32:00.340 INFO methods.StartAndRun:30 - Thread Running...

运行测试方法 testStartMethod() ,调用 start() 方法后,日志打印的线程有 [Test worker], [t1] , 方法的调用是异步的。

03 小结

  • 直接调用 run() 方法,并没有启动新的线程
  • 使用 start() 是启用新的线程,通过新的线程执行 run() 中的方法