下面是一个使用继承Thread类创建线程并循环打印输出的示例代码: ```java public class MyThread extends Thread { public MyThread(String name) { super(name); } @Override public void run() { for (int i = 1; i <= 10; i++) { System.out.println(getName() + ": " + i); } } public static void main(String[] args) { MyThread thread1 = new MyThread("Thread 1"); MyThread thread2 = new MyThread("Thread 2"); thread1.start(); thread2.start(); } } ``` 这段代码创建了一个MyThread类,继承自Thread类。在MyThread类的run()方法中,使用循环打印输出线程名和循环变量的值。在main()方法中,创建了两个MyThread对象,并分别启动这两个线程。 运行上述代码会得到如下的输出结果: ``` Thread 1: 1 Thread 2: 1 Thread 1: 2 Thread 2: 2 Thread 1: 3 Thread 2: 3 Thread 1: 4 Thread 2: 4 Thread 1: 5 Thread 2: 5 Thread 1: 6 Thread 2: 6 Thread 1: 7 Thread 2: 7 Thread 1: 8 Thread 2: 8 Thread 1: 9 Thread 2: 9 Thread 1: 10 Thread 2: 10 ``` 可以看到,两个线程交替执行,并且打印了各自的线程名和循环变量的值。 [2024-05-24 10:48:31 | AI写代码神器 | 720点数解答]