1.随便选择两个城市作为预选旅游目标。实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000ms以内),哪个先显示完毕,就决定去哪个城市。分别用Runnable接口和Thread类实现。
package Thanqi; public class Chengshi extends Thread { private String city; public Chengshi(String city)
{
this.city=city;
}
public void run(){
for(int i =0;i<10;i++)
{System.out.println(city);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
} } }
package Thanqi; public class TestCity { public static void main(String[] args) { Chengshi c1= new Chengshi("城市1"); c1.start(); //用新线程调用run方法 Chengshi c2= new Chengshi("城市2"); c2.start(); //用新线程调用run方法 } }