江南飞鹏 2016-12-01 12:02 采纳率: 0%
浏览 825

这个问题该如何解决啊,求大神指点

选择两个城市作为预选旅游目标,实现两个独立的线程分别显示10次城市名,每次显示后休眠一段随机时间(1000毫秒以内),哪个先显示完毕,就决定去哪个城市。请用Runnable接口或Thread类实现。

下面是用Thread类的实现,参考程序如下,用Runable接口实现方法类似。
public class Ex82 {
public static void main(String[] args){
String[] citys = {"合肥","淮南"};
ThreadCity1 thread1 = new ThreadCity1(citys);
ThreadCity2 thread2 = new ThreadCity2(citys);
thread1.start();
thread2.start();
/*
* 请在下面补充几行代码,保证thread1和thread2都允许结束再执行后面的if语句。
*/
While(thread1.isAlive() || thread2.isAlive()){
}
if(thread1.getTime()<thread2.getTime()){
System.+
out.println("决定去:"+citys[0]);
}
else{
System.out.println("决定去:"+citys[1]);
}

 }

}

class ThreadCity1 extends Thread{
private String[] citys;
private long time;
public long getTime(){
return time;
}
ThreadCity1(String[] citys){
this.citys=citys;
}
public void run(){
long start = System.currentTimeMillis();
for(int i=0;i<10;i++){
try{
System.out.println("Thread1:"+citys[0]);
Thread.sleep((int)(Math.random()*1000));
}
catch(Exception e){

        }
    }
   time = System.currentTimeMillis() - start;   
   System.out.println("Thread1 Ends!");
}

}

class ThreadCity2 extends Thread{
private String[] citys;
private long time;
public long getTime(){
return time;
}
ThreadCity2(String[] citys){
this.citys=citys;
}
public void run(){
long start = System.currentTimeMillis();
for(int i=0;i<10;i++){
try{
System.out.println("Thread2:"+citys[1]);
Thread.sleep((int)(Math.random()*1000));
}
catch(Exception e){

        }
    }
   time = System.currentTimeMillis() - start;   
   System.out.println("Thread2 Ends!");
}

}

  • 写回答

1条回答 默认 最新

  • weixin_36880174 2016-12-01 13:19
    关注

    我在帖子那边回复你了,我也是刚学到多线程。。。很多都不是很懂。。。

    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable