我写了个程序,Main方法执行的时候需要传递一个参数,假如传入猫的话,程序就会执行猫的一系列动作代码等,假如传入狗的话,程序就会执行狗的一系列动作代码等。但是现在我需要的是 这一个程序启动的时候既能执行狗也能执行猫?该如何实现呢????我想过用多线程,但是试了下,只要有其中一个线程挂掉 整个程序就挂掉了,该怎么办呢?????
解决方案 »
- 关于rmi的问题
- 急急。。谁能把这个俄罗斯方块“新游戏”,“暂停”,“继续”的功能补充啊!!
- Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
- Java进度条的疑难问题
- 一个关于“可变参数列表”的问题
- 救我:tomcat不能启动
- 这两个声明是不是完全一样的
- 如何使用JAVA获取WINDOWS的网站访问历史记录
- 请问 >>>什么是Java 的核心技术?<<<
- ▲▲▲为什么我得到的网页时间和大小有问题啊▲▲▲
- 反序列化时抛出了IllegalAccessException
- 为什么放入TreeSet中的对象在实现了comparable接口后,曾经override过的equals,hashCode方法都不起作用了。
用while把逻辑包起来不行么?
while(flog){
if(猫){
//猫
}else if(狗){
//狗
}else{
flog = flase;
}
}
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("狗");
}
}不知道可不可以
import java.io.FileNotFoundException;
import java.lang.reflect.*;
这是引入多余的
你要并发同时做几件事情,要通过多线程,大概如下(你自己根据真实情况调整):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();
}
}