【问题标题】:Do we override run method when child class is extended from thread parent class当子类从线程父类扩展时,我们是否覆盖运行方法
【发布时间】:2010-11-12 03:33:51
【问题描述】:

当我们子类化线程时,我们是否覆盖它的运行方法?我们知道 Thread 类本身实现了 Runnable,但是 Runnable 类中没有定义 run 方法的主体。

这是我脑海中的画面:

Runnable - 父类 - 它有一个 run 方法,主体为空。

线程-子,

classA 扩展了 Thread- Child of Child,

当我们在 "classA" 中定义 run() 方法时,我们是否覆盖了 Runnable 类中声明的 run 方法? 感谢您的宝贵时间。

【问题讨论】:

    标签: java multithreading thread-safety


    【解决方案1】:

    有两种方法可以定义线程的行为:子类化 Thread 类,或者实现 Runnable 接口。

    对于第一种方法,只需扩展 Thread 类并使用您自己的实现覆盖 run() 方法:

    public class HelloThread extends Thread {
        @Override
        public void run() {
            System.out.println("Hello from a thread!");
        }
    }
    
    public class Main { 
        // main method just starts the thread 
        public static void main(String args[]) {
            (new HelloThread()).start();
        }
    }
    

    但是,实现线程逻辑的首选方法是创建一个实现 Runnable 接口的类:

    public class HelloRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("Hello from a thread!");
        }
    }
    
    public class Main {
        // notice that we create a new Thread and pass it our custom Runnable
        public static void main(String args[]) {
            (new Thread(new HelloRunnable())).start();
        }
    }
    

    首选实现 Runnable 的原因是它在线程的行为和线程本身之间提供了清晰的分离。例如,当使用线程池时,您永远不会真正从头开始创建线程,您只需将 Runnable 传递给框架,它会在您可用的线程上执行它:

    public class Main {
        public static void main(String args[]) {
            int poolSize = 5;
            ExecutorService pool = Executors.newFixedThreadPool(poolSize);
            pool.execute(new HelloRunnable());
        }
     }
    

    进一步阅读:

    【讨论】:

    • 这是非常好的信息,但我没有得到答案,我们是否覆盖了 Thread 类中定义的 run 方法。
    • @ranjanarr 再次阅读答案。特别是第二句。
    【解决方案2】:

    你应该扩展线程,只有当你打算重写线程的功能或提高它的性能。

    接口告诉你,如果你使用这个接口,你将获得功能性。在你的情况下,你的业务逻辑需要在一个线程中运行然后使用接口。

    如果你有更好的方式来有效地运行线程,那么扩展线程。

    【讨论】:

      猜你喜欢
      • 2018-07-08
      • 2017-08-17
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多