1

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

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 
}
}

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

4

3 回答 3

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();
                }
            });

    }
}

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

于 2012-04-29T15:37:15.300 回答
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));
于 2012-04-29T15:38:21.077 回答
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();
于 2012-04-29T15:42:03.767 回答