创建一个test1类以继承Thread类,重写run()方法,分别在main()方法和其他线程中使用for循环输出信息。
乘法表就这样,test1 for循环输出什么内容呢
public class Test9 {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(j + " * " + i + " = " + (i * j) + "\t");
}
System.out.println();
}
}
}
public class test1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("thread: " + Thread.currentThread().getName());
}
}
public static void main(String[] args) {
// 创建并启动新线程
test1 test1 = new test1();
test1.start();
// 在主线程中使用 for 循环输出信息
for (int i = 0; i < 5; i++) {
System.out.println("main: " + Thread.currentThread().getName());
}
}
}
优点:在run()方法中无需使用Thread.currentThread()方法获取当前线程,可以直接使用this;方便传参,可以在子类中添加成员变量,通过set的方式设置参数或者是构造函数
缺点:在java语言中不支持多继承,在你继承了Thread之后,不可以在去继承其他的类了
public class Test9 extends Thread{
public void run(){
for(int i =1; i<=9; i++){
for(int j=1; j<=i; j++){
System.out.print(i+"*"+j+"="+i*j+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
Test9 test = new Test9();
test.start();
for(int i=1; i<=9; i++){
for(int j=1; j<=i; j++){
System.out.print(i+"*"+j+"="+i*j+" ");
}
System.out.println();
}
}
}
在这个代码中,我们首先定义一个类Test9继承自Thread类,然后重写父类的run()方法。在run()方法中,我们使用两个for循环来实现乘法口诀表。最后,我们在main()方法中分别启动一个线程和直接用for循环输出乘法口诀表。由于Test9继承自Thread类,所以我们可以在run()方法中直接使用getName()方法来获取线程的名字。使用start()方法来启动线程,这样就可以在子线程中执行run()方法来输出乘法口诀表了。