java代码实现采用继承Thread方法实现2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
时间: 2023-07-15 13:15:58 浏览: 54
以下是实现的Java代码:
```java
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(this.getName() + "-" + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread1");
MyThread thread2 = new MyThread("Thread2");
thread1.start();
thread2.start();
}
}
```
首先定义一个继承自Thread的MyThread类,重写run方法,在其中循环输出“线程名-数字”。然后在主函数中创建两个MyThread对象,并调用start方法启动两个线程。这样就可以实现两个线程同时循环输出“线程名-数字”的效果。
相关问题
用继承thread方法完成Java程序实现:2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
以下是使用继承Thread类方法实现的Java示例代码:
```java
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(name + "-" + i);
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}
```
在上面的代码中,创建了一个名为 `MyThread` 的自定义线程类,该类继承了 Java 内置的 `Thread` 类。在 `run` 方法中,使用循环输出线程名和数字。然后在 `Main` 类中创建两个线程 `thread1` 和 `thread2`,并启动它们。最后使用 `join` 方法等待两个线程结束。
写一个Java程序通过继承Thread的方法实现2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
以下是实现上述要求的Java程序:
```
public class MyThread extends Thread {
private String threadName;
public MyThread(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(threadName + "-" + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread1");
MyThread thread2 = new MyThread("Thread2");
thread1.start();
thread2.start();
}
}
```
在这个程序中,我们定义了一个名为`MyThread`的类,这个类继承自`Thread`类,并重写了`run()`方法。在`run()`方法中,我们使用一个`for`循环输出指定的字符串。
在`Main`类中,我们创建了两个`MyThread`对象,并通过调用它们的`start()`方法来启动线程。当线程被启动时,它们会自动调用`run()`方法,并且在循环中输出指定的字符串。
注意:由于线程是并发执行的,因此输出结果可能会交错出现。