通过继承 Thread 类设计两个线程,其中: (1) 一个线程,类名为 FirstThread,打印 'a' ~ 'z'; (2) 另一个线程,类名为 SecondThread,打印 1~50; (3) 编写测试类 TestThread,在其 main( )方法中创建并启动这两个线程。
时间: 2023-11-22 09:56:05 浏览: 41
下面是一个简单的实现:
```
class FirstThread extends Thread {
public void run() {
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c + " ");
}
}
}
class SecondThread extends Thread {
public void run() {
for (int i = 1; i <= 50; i++) {
System.out.print(i + " ");
}
}
}
public class TestThread {
public static void main(String args[]) {
FirstThread firstThread = new FirstThread();
SecondThread secondThread = new SecondThread();
firstThread.start();
secondThread.start();
}
}
```
在这个实现中,我们创建了两个线程:`FirstThread` 和 `SecondThread`,分别打印字母和数字。这两个线程都继承了 `Thread` 类,并重写了 `run()` 方法,该方法定义了线程的行为。
在 `TestThread` 类的 `main()` 方法中,我们创建了 `FirstThread` 和 `SecondThread` 的实例,并调用它们的 `start()` 方法来启动线程。当线程被启动时,它们会自动调用 `run()` 方法,并执行定义的行为。在本例中,`FirstThread` 和 `SecondThread` 并行执行,打印字母和数字。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)