从我在Java中使用线程的时间来看,我发现了两种编写线程的方法:

使用可运行的机具:

public class MyRunnable implements Runnable {
    public void run() {
        //Code
    }
}
//Started with a "new Thread(new MyRunnable()).start()" call

或者,使用扩展线程:

public class MyThread extends Thread {
    public MyThread() {
        super("MyThread");
    }
    public void run() {
        //Code
    }
}
//Started with a "new MyThread().start()" call

这两个代码块有什么显著的区别吗?


当前回答

我想说还有第三种方法:

public class Something {

    public void justAnotherMethod() { ... }

}

new Thread(new Runnable() {
   public void run() {
    instanceOfSomething.justAnotherMethod();
   }
}).start();

也许这受到了我最近大量使用Javascript和Actionscript 3的影响,但是这样你的类就不需要实现一个非常模糊的接口,比如Runnable。

其他回答

您可以共同使用它们

例子:

public class A implements Runnable{

    @Override
    public void run() {


        while(true){
             System.out.println("Class A is running");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }}

    }

}



public class Test {

    public static void main(String[] args) {

        Thread myThread =new Thread(new A());// 1
        myThread.start();
        System.out.println(" executed after thread A");//will never be reached

    }

} 

对如果调用ThreadA调用,则不需要调用start方法,run方法只在调用ThreadA类后调用。但如果使用ThreadB调用,则需要启动线程来调用run方法。如果你还有什么帮助,请回复我。

我不是专家,但我能想到实现Runnable而不是扩展Thread的一个原因:Java只支持单一继承,因此只能扩展一个类。

编辑:这原本是说“实现一个接口需要更少的资源”,但无论如何都需要创建一个新的线程实例,所以这是错误的。

通过扩展线程类,派生类不能扩展任何其他基类,因为java只允许单一继承。相反,通过实现可运行接口,类仍然扩展了其他基类。

实现Runnable和扩展Thread之间最显著的区别如下:

通过扩展Thread,派生类本身就是一个线程对象,而实现Runnable接口则将同一对象共享给多个线程。

您希望实现接口而不是扩展基类的一个原因是您已经在扩展其他类。您只能扩展一个类,但可以实现任意数量的接口。

如果扩展Thread,基本上就是防止逻辑被除“this”之外的任何其他线程执行。如果您只希望一些线程执行您的逻辑,那么最好只实现Runnable。