通过当前线程调用多个方法

时间:2012-04-29 15:27:42

标签: java multithreading

假设我们有这些课程并阅读评论

class Work {
void doWork(){  }
void commit(){}       
}
class MyRunable implements Runnable {
run(){
   Work  work=new Work();
   work.doWork();
//i can't write work.commit() here, because sometimes i want Thread runs both methods       
 //and sometimes runs only doWork()
 }
}
class Tasks{
main(){
MyRunable myRunable=new MyRunable();
Thread t=new Thread(myRunable);
t.start();
//suppose now i need to call commit() method by the same thread (t)
//how can i do that 
}
}

我也不想使用构造函数来确定我是否要同时调用这两种方法

3 个答案:

答案 0 :(得分:1)

您可以尝试使用具有单个线程的线程池,并根据需要继续排队方法:

class Tasks {
    public static void main(String[] args) {            

        ExecutorService exec = Executors.newSingleThreadExecutor();
        final Work work = new Work();
        exec.submit(new Runnable() {
                public void run() {
                    work.doWork();
                }
            });
        // later
        exec.submit(new Runnable() {
                public void run() {
                    work.commit();
                }
            });

    }
}

这样,两个方法将由同一个线程按顺序执行,但是单独执行。

答案 1 :(得分:0)

为您的班级MyRunnable添加参数。将此参数称为“runingMode”。它可能是一个枚举:

enum RunningMode {
    DO_WORK {
        public void work(Work work) {
             work.doWork();
        }
    },
    COMMIT {
        public void work(Work work) {
             work.commit();
        }
    };
    public abstract void work();
}

现在你的班级MyRunnable应该有模式列表:

class MyRunable implements Runnable {
    private Collection<RunningMode> modes;
    MyRunable(Collection<RunningMode> modes) {
         this.modes = modes;
    }
}

实施run()方法如下:

  Work  work=new Work();
  for (RunningMode mode : modes) {
        mode.work(work);
  }
  work.doWork();

创建您的类的实例,向其传递您当前需要的模式:

MyRunable myRunable=new MyRunable(Arrays.asList(RunningMode.DO_WORK, RunningMode.COMMIT));

答案 2 :(得分:0)

您可以使用匿名类。

final boolean condition = ...
Thread t = new Thread(new Runnable() {
  public void run() {
    Work work=new Work();
    work.doWork();
    if(condition)
       work.commit();
}});
t.start();