将Thread对象传递给Exceutor.execute为什么没有道理?

来源:百度知道 编辑:UC知道 时间:2024/09/21 20:34:15
The Java Tutorial中关于并行的篇章中的练习有这样一段:
Question: Can you pass a Thread object to Executor.execute? Would such an invocation make sense? Why or why not?

Answer: Thread implements the Runnable interface, so you can pass an instance of Thread to Executor.execute. However it doesn't make sense to use Thread objects this way. If the object is directly instantiated from Thread, its run method doesn't do anything. You can define a subclass of Thread with a useful run method — but such a class would implement features that the executor would not use.
关于最后一句话我不太理解,请高手指点一下,谢谢!

翻译:
Thread类实现Runnable接口,所以你可以传递一个Thread的实例到Executor.execute。 然而这样使用Thread对象不起任何作用没什么意义。如果这个对象是Thread的一个直接实例,它的run方法不做任何事情。你可以定义一个Thread类的子类,在子类中实现一个可用的run()--但是这个类需要实现那些executor 无法使用的特性。

解释:
意思是说,可以传递一个Thread的对象进去,但是如果这个对象是直接用Thread类new出来的,即:
Thread t = new Thread();
把t传进去是不能用的,因为run()方法是空的,没有实现。

要想可用,需要从Thread的一个子类创建实例,这个子类要实现一个可用的run()方法,当然可能还有别的方法,这些别的方法在executor中是不能用的(因为不是父类中的方法)。

class MyThread extends Thread{
/**
* 实现一个可用的run方法
*/
public void run(){
//do something
}
/**
* 其他方法,这些方法不是Thread类中方法的重写
* 在executor 中这个方法是不能使用的。因为这个方法属于Thread的子类,不是Thread中的方法或接口
*/
public void methodA(){
//do something
}
/**
* 同methodA
*/
public void methodB(){
//do something
}
}

此时,定义Thread t = new MyThread(),把t传入executor 中就可用了,因为run方法实现了。但是executor 中不能使用t的methodA和methodB方法,因为这两个方法是子类MyThread加上去的方法,不是来自父类Thread的方法或接口。

启动进程了吗