如果我们直接调用run方法会怎样? [英] what will happen if we directly call run method?

查看:263
本文介绍了如果我们直接调用run方法会怎样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个"TestRunnable"类,它通过实现Runnable覆盖了run方法. 运行覆盖的运行方法,如下所示:

I have a class "TestRunnable" which overrides run method by implementing Runnable. Running overridden run method, as follow :

TestRunnable nr = new TestRunnable();
Thread t = new Thread(nr);
t.setName("Fred");
t.start();

  • 如果我直接拨打t.run();
  • 该怎么办
  • 如果我们不拨打t.start();会发生什么?
    • What if i directly call t.run();
    • What happen if we don't call t.start(); ?
    • 推荐答案

      run方法只是另一种方法.如果直接调用它,那么它将不在另一个线程中执行,而是在当前线程中执行.

      The run method is just another method. If you call it directly, then it will execute not in another thread, but in the current thread.

      这是我的考试TestRunnable:

      class TestRunnable implements Runnable
      {
         public void run()
         {
            System.out.println("TestRunnable in " + Thread.currentThread().getName());
         }
      }
      

      仅调用start时的输出:

      TestRunnable in Fred
      

      仅调用run时的输出:

      TestRunnable in main
      

      如果未调用start,则创建的Thread将永远不会运行.主线程将完成,Thread将被垃圾回收.

      If start isn't called, then the Thread created will never run. The main thread will finish and the Thread will be garbage collected.

      如果两者都不被调用,则输出:(无)

      Output if neither is called: (nothing)

      这篇关于如果我们直接调用run方法会怎样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆