首先看一下Runnable接口
的源码,整个方法体里就只有一个run的抽象方法,所以才创建实现类实现该接口的时候是肯定要重写接口内的抽象方法的(也就是run()方法
),按照重写规则(不能是抽象,参数要和父类一致,也就是无参)重写run()方法
,方法体就可以自定义添加了。
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
但是我在百度上找到了这么一个题
能看到run()方法
的参数是Thread t
,并不是无参但是能够成功运行,以下是run()方法
可以带参的情况:
要实现带参数的
run()方法
:
- 定义线程内变量;
- 在继承thread的时候,增加带参数的构造函数,初始化线程内变量;
- 在run方法操作线程内变量,以达到类似传参的效果。
示例:
class MyThread extends Thread{
int a = 0;//定义线程内变量
public MyThread(int a){//定义带参数的构造函数,达到初始化线程内变量的值
this.a=a;
}
@Override
public void run() {
this.a++;//线程内变量自增
}
}
引用一位网友的回答补充说明