Thread.run or Thread.start

客官°小女子只卖身不卖艺 2022-06-02 01:16 347阅读 0赞

Common Pitfall: Calling run() Instead of start()

When creating and starting a thread a common mistake is to call the run() method of the Thread instead of start(), like this:

  1. Thread newThread = new Thread(MyRunnable());
  2. newThread.run(); //should be start();

At first you may not notice anything because the Runnable’s run() method is executed like you expected. However, it is NOT executed by the new thread you just created. Instead the run() method is executed by the thread that created the thread. In other words, the thread that executed the above two lines of code. To have the run() method of the MyRunnable instance called by the new created thread, newThread, you MUST call the newThread.start() method.

示例:

TestRunnable.java

  1. public class TestRunnable implements Runnable {
  2. private StopWatch stopWatch;
  3. public TestRunnable() {
  4. stopWatch = new StopWatch();
  5. }
  6. @Override
  7. public void run() {
  8. stopWatch.start();
  9. System.out.println("TestRunnable start");
  10. try {
  11. Thread.sleep(5000);
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. System.out.println(String.format("TestRunnable end %s", stopWatch.getTime()));
  16. }
  17. }

Thread.start()方法

  1. public class TestRunnableMain {
  2. public static void main(String[] args) {
  3. System.out.println("TestRunnableMain start");
  4. TestRunnable testRunnable = new TestRunnable();
  5. Thread thread = new Thread(testRunnable);
  6. thread.start();
  7. System.out.println("TestRunnableMain end");
  8. }
  9. }

执行结果:

TestRunnableMain start
TestRunnableMain end
TestRunnable start
TestRunnable end 5012

Thread.run()方法

  1. public class TestRunnableMain {
  2. public static void main(String[] args) {
  3. System.out.println("TestRunnableMain start");
  4. TestRunnable testRunnable = new TestRunnable();
  5. Thread thread = new Thread(testRunnable);
  6. thread.run();
  7. System.out.println("TestRunnableMain end");
  8. }
  9. }

执行结果:

TestRunnableMain start
TestRunnable start
TestRunnable end 5009
TestRunnableMain end

http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html

发表评论

表情:
评论列表 (有 0 条评论,347人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Mysql 优化 or

    Mysql 优化 or or 关键字连接的两边条件都是索引字段,执行计划如下 ![img][] or 关键字连接的两边条件,一个是索引字段,另外一个是非索引字段,执行

    相关 经验 OR 学历?

             经验 or 学历?有时一个矛盾的问题,都大三了,该好好的考虑一下自己的未来了,决定自己的未来。 一个很头疼的问题摆在自己的面前,毕业了是直接去工作,还是去考

    相关 AND & OR

    AND 和 OR 运算符用于基于一个以上的条件对记录进行过滤。 AND 和 OR 运算符 AND 和 OR 可在 WHERE 子语句中把两个或多个条件结合起来。 如果

    相关 Ebean or 语法

    原生SQL语句使用or的时候我们通常会这么写: ![在这里插入图片描述][20200914101700527.png_pic_center] 那么使用Ebean的时候我

    相关 and or php,AND OR

    \\ AND OR 上面是基础的Where语句,下面看一下复杂一点的 你可以使用"AND" 或 "OR" 来拼接非常复杂的SQL语句 ~~~ namespace Act

    相关 Safe Or Unsafe

    题目描述: Javac++ 一天在看计算机的书籍的时候,看到了一个有趣的东西!每一串字符都可以被编码成一些数字来储存信息,但是不同的编码方式得到的储存空间是不一样的!并且