Java线程类public void run()方法(带示例)
线程类publicvoidrun()
包java.lang.Thread.run()中提供了此方法。
线程的run()方法包含线程的可执行代码。
此方法不是静态的,因此我们也无法使用类名访问此方法。
线程类包含run()具有空实现的方法。
我们可以run()在类中重载方法,但是Thread类start()默认情况下仅调用默认run()方法,如果要调用另一个run()方法,则需要像普通方法一样显式调用。
如果我们run()在类中重写该方法,则它包含任务,因此我们的线程负责执行此方法。
如果我们不在run()类中重写方法,则该run()方法将由Thread类执行,并且由于Thread类定义的run()方法的实现为空,因此不会获得任何输出。
此方法的返回类型为void,因此它不返回任何内容。
语法:
public void run(){
}参数:
当我们编写t.start()时,此行表示start()Thread的调用方法和Thread类start()将调用run()我们定义的类的方法。
返回值:
此方法的返回类型为void,它不返回任何内容。
Java程序演示run()方法示例
/* We will use Thread class methods so we are
importing the package but it is not mandate
because it is imported by default
*/
import java.lang.Thread;
class MyThread extends Thread {
//run()Thread类的重写方法
public void run() {
System.out.println("We are in run() method of MyThread thread");
}
}
class Main {
public static void main(String[] args) {
//这里我们调用run()MyThread的方法
//像普通方法一样的类
MyThread mt = new MyThread();
mt.run();
//这里我们在调用start()Thread类的方法
//它将调用run()MyThread的方法
mt.start();
//这里我们在调用run()Thread类的方法
Thread t = new Thread();
t.run();
}
}输出结果
E:\Programs>javac Main.java E:\Programs>java Main We are in run() method of MyThread thread We are in run() method of MyThread thread
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短