java 编写程序请用三种方法完成:2个线程同时循环输出“线程名-数字”,其中数字从1变化到10.
时间: 2023-11-27 07:52:55 浏览: 74
方法一:使用继承Thread类的方式
```java
public class ThreadDemo extends Thread {
private String threadName;
public ThreadDemo(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(threadName + "-" + i);
}
}
public static void main(String[] args) {
ThreadDemo thread1 = new ThreadDemo("Thread A");
ThreadDemo thread2 = new ThreadDemo("Thread B");
thread1.start();
thread2.start();
}
}
```
方法二:使用实现Runnable接口的方式
```java
public class ThreadDemo implements Runnable {
private String threadName;
public ThreadDemo(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(threadName + "-" + i);
}
}
public static void main(String[] args) {
ThreadDemo thread1 = new ThreadDemo("Thread A");
ThreadDemo thread2 = new ThreadDemo("Thread B");
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t1.start();
t2.start();
}
}
```
方法三:使用匿名内部类的方式
```java
public class ThreadDemo {
public static void main(String[] args) {
Runnable r1 = new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread A-" + i);
}
}
};
Runnable r2 = new Runnable() {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread B-" + i);
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
}
```
阅读全文