我写了个程序,Main方法执行的时候需要传递一个参数,假如传入猫的话,程序就会执行猫的一系列动作代码等,假如传入狗的话,程序就会执行狗的一系列动作代码等。但是现在我需要的是 这一个程序启动的时候既能执行狗也能执行猫?该如何实现呢????我想过用多线程,但是试了下,只要有其中一个线程挂掉 整个程序就挂掉了,该怎么办呢?????

解决方案 »

  1.   

    挂掉是啥意思?执行结束?如果我猜测正确的话
    用while把逻辑包起来不行么?
    while(flog){
      if(猫){
        //猫
      }else if(狗){
        //狗
      }else{
        flog = flase;
      }
    }
      

  2.   

    import java.util.*;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.lang.reflect.*;public class Test {
    String s;
     Test(String s)
    {
    this.s=s;
    }
     public static void main(String[] args)  {
     Scanner scanner=new Scanner(System.in);
     System.out.println("输入猫或狗:");
     String  name=scanner.next();
     new Test(name).begin();
        }
        public  void begin(){
    if(this.s.equals("猫"))
    {
    thread1 t1=new thread1();
    t1.start();
    }
    else if(this.s.equals("狗")){
    thread2 t2=new thread2();
    t2.start();
    }
    }
    }class thread1 extends Thread{

    public void run(){

    System.out.println("猫");
    }
    }
    class thread2 extends Thread{

    public void run(){

    System.out.println("狗");
    }
    }不知道可不可以
      

  3.   

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.lang.reflect.*;
    这是引入多余的
      

  4.   

    首先先纠正一个问题:“只要有其中一个线程挂掉 整个程序就挂掉了”,这个是不可能的,是你自己代码写的问题。
    你要并发同时做几件事情,要通过多线程,大概如下(你自己根据真实情况调整):public interface Animal {
    void action();
    }public class Dog implements Animal {
    public void action() {
    System.out.println("Dog");
    }
    }public class Cat implements Animal {
    public void action() {
    System.out.println("Cat");
    }
    }public AnimalThread implements Runnable {
    private Animal animal;
    public AnimalThread (Animal animal) {
    this.animal = animal;
    }

    public void run() {
    animal.action();
    }
    }public class AnimalExecutor {
    public static void main(String[] args) {
    Thread dogExecutor = new Thread(new AnimalThread(new Dog()));
    Thread catExecutor = new Thread(new AnimalThread(new Cat()));
    dogExecutor.start();
    catExecutor.start();
    }
    }