从我在Java中使用线程的时间开始,我发现了这两种编写线程的方法:
用implements Runnable:
public class MyRunnable implements Runnable {
public void run() {
//Code
}
}
//Started with a "new Thread(new MyRunnable()).start()" call
Run Code Online (Sandbox Code Playgroud)
或者,用extends Thread:
public class MyThread extends Thread {
public MyThread() {
super("MyThread");
}
public void run() {
//Code
}
}
//Started with a "new MyThread().start()" call
Run Code Online (Sandbox Code Playgroud)
这两个代码块有什么显着差异吗?
Java Thread本身实现了Java Runnable!并且根据Internet上的大多数专家,实现Runnable比扩展Thread更受欢迎!即使我们不能在Thread类的线程意义上使用Runnable!
那么为什么我们更喜欢实现Runnable过度扩展,Thread因为在这两种情况下,通过调用一个Thread实现的方法(即start()或者run())来说明实际的线程,尽管在Thread我们没有真正"扩展" Thread仅通过覆盖run()方法的功能的情况下?
如果我听起来很混乱,我道歉......