选择两个城市作为预选旅游目标,实现两个独立的线程分别显示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.   

    使用lang.Process.waitFor()方法
    举个例子
    public class ProcessDemo {   public static void main(String[] args) {
          try {
             // create a new process
             System.out.println("Creating Process...");
             Process p = Runtime.getRuntime().exec("notepad.exe");         // cause this process to stop until process p is terminated
             p.waitFor();         // when you manually close notepad.exe program will continue here
             System.out.println("Waiting over.");      } catch (Exception ex) {
             ex.printStackTrace();
          }   }
    }