class SimpleThread extends Thread( public SimpleThread(String str){ sper(st:/调用其父类的构造方法 public void runO【重写run方法 for (int i-0;i<10;i++){ Systemout.println(i+""+getNameO); try sleep(int Math random0*1000);/线程睡眠,把控制权交出 catch (InterruptedException e){ System.out println("DONEI"+getNameO): public class TwoThreadsTest( public static void main (String args[D{ new SimpleThread("First')start0:/第一个线程的名字为First new SimpleThread("Second')startO;/第二个线程的名字为Second
时间: 2024-03-31 18:35:25 浏览: 10
这段代码展示了一个简单的多线程程序,包括一个继承了Thread类的SimpleThread类和一个包含main方法的TwoThreadsTest类。SimpleThread类重写了Thread类的run方法,实现了线程的执行逻辑,包括打印线程名和随机睡眠一段时间。TwoThreadsTest类创建了两个SimpleThread对象,并启动它们,分别输出线程名和睡眠时间。这个程序展示了如何使用多线程实现并发执行任务,提高程序效率。
相关问题
用Runnable接口编写class SimpleThread extends Thread { public SimpleThread(String str) { super( str ); } public void run() { for (int i = 0; i < 10; i++) { System.out.println( i + "" + getName() ); try { sleep( (int) (Math.random() * 1000) ); } catch (InterruptedException e) { } } System.out.println( "DONE!" + getName() ); } }public class TwoThreadsTest { public static void main(String args[]) { new SimpleThread( "First" ).start(); new SimpleThread( "Second" ).start(); } }
可以使用 Runnable 接口来实现类似的功能。修改后的代码如下:
```
class SimpleRunnable implements Runnable {
private String name;
public SimpleRunnable(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + "" + name);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
System.out.println("DONE!" + name);
}
}
public class TwoThreadsTest {
public static void main(String args[]) {
new Thread(new SimpleRunnable("First")).start();
new Thread(new SimpleRunnable("Second")).start();
}
}
```
这里,定义了一个实现了 Runnable 接口的 SimpleRunnable 类,其中包含一个 name 属性,用于存储线程的名称。在 run() 方法中,执行了和之前一样的循环和输出操作。最后,在 main() 方法中,创建了两个线程,并将 SimpleRunnable 对象作为参数传递给 Thread 构造函数。然后,通过 start() 方法启动线程。运行结果和之前的例子类似。
运行结果class SimpleThread extends Thread { public SimpleThread(String str) { super( str ); } public void run() { for (int i = 0; i < 10; i++) { System.out.println( i + "" + getName() ); try { sleep( (int) (Math.random() * 1000) ); } catch (InterruptedException e) { } } System.out.println( "DONE!" + getName() ); } }public class TwoThreadsTest { public static void main(String args[]) { new SimpleThread( "First" ).start(); new SimpleThread( "Second" ).start(); } }
运行结果可能会不同,因为涉及到线程并发执行的情况。但是,每个线程都会输出从 0 到 9 的数字以及自己的名称,并且随机睡眠一段时间。最后,在循环结束时,每个线程会输出 "DONE!" 和自己的名称。可能的输出结果类似于:
```
0First
0Second
1First
1Second
2First
2Second
3First
3Second
4First
4Second
5First
DONE!First
5Second
6First
6Second
7First
7Second
8First
8Second
9First
DONE!Second
9Second
DONE!First
```