随便选择两个城市作为预选旅游目标,实现两个独立线程分别显示10次城市名,每显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
时间: 2023-06-25 10:04:34 浏览: 107
使用Runnable接口实现:
```java
import java.util.Random;
public class TravelRunnable implements Runnable {
private String city;
private Random random = new Random();
public TravelRunnable(String city) {
this.city = city;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(city);
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
使用Thread类实现:
```java
import java.util.Random;
public class TravelThread extends Thread {
private String city;
private Random random = new Random();
public TravelThread(String city) {
this.city = city;
}
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(city);
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
在主函数中创建两个线程,并启动:
```java
public class Main {
public static void main(String[] args) {
TravelRunnable thread1 = new TravelRunnable("北京");
TravelThread thread2 = new TravelThread("上海");
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("去" + (thread1.isAlive() ? "上海" : "北京"));
}
}
```
在主函数中,我们创建了两个线程,一个使用Runnable接口实现,一个使用Thread类实现。然后启动这两个线程,并使用join()方法等待它们执行结束。最后,根据哪个线程先执行结束,就决定去哪个城市。
阅读全文