java 求各路大神指教!!!!

wpython111 2012-10-16 10:32:15
我写了个程序,Main方法执行的时候需要传递一个参数,假如传入猫的话,程序就会执行猫的一系列动作代码等,假如传入狗的话,程序就会执行狗的一系列动作代码等。但是现在我需要的是 这一个程序启动的时候既能执行狗也能执行猫?该如何实现呢????我想过用多线程,但是试了下,只要有其中一个线程挂掉 整个程序就挂掉了,该怎么办呢?????
...全文
138 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
蓝蜘蛛 2012-10-18
  • 打赏
  • 举报
回复
还要用到监听器,当传入参数是猫时,启动猫线程,狗时启动狗线程,同时传,同时启动,运行结束别忘记关闭线程
如果对参数还有更多要求时,比如吃饭,散步,叫3种方法对应不同动作
就要对动作进行监听而不是对线程启动进行监听
zxhcloth 2012-10-18
  • 打赏
  • 举报
回复
首先先纠正一个问题:“只要有其中一个线程挂掉 整个程序就挂掉了”,这个是不可能的,是你自己代码写的问题。
你要并发同时做几件事情,要通过多线程,大概如下(你自己根据真实情况调整):

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();
}
}
licip 2012-10-18
  • 打赏
  • 举报
回复
上你代码看看吧。
wpython111 2012-10-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

挂掉是啥意思?执行结束?

如果我猜测正确的话
用while把逻辑包起来不行么?
while(flog){
if(猫){
//猫
}else if(狗){
//狗
}else{
flog = flase;
}
}
[/Quote]我的需求是并发执行,这样不行的啊
蓝蜘蛛 2012-10-16
  • 打赏
  • 举报
回复
挂掉是啥意思?执行结束?

如果我猜测正确的话
用while把逻辑包起来不行么?
while(flog){
if(猫){
//猫
}else if(狗){
//狗
}else{
flog = flase;
}
}
wpython111 2012-10-16
  • 打赏
  • 举报
回复
有什么其他的好办法么?
aimsgmiss 2012-10-16
  • 打赏
  • 举报
回复
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.reflect.*;
这是引入多余的
aimsgmiss 2012-10-16
  • 打赏
  • 举报
回复
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("狗");
}
}

不知道可不可以

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧