繁体   English   中英

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

[英]call more than one methode by current thread

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

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

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

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

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

    }
}

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

将参数添加到类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));

您可以使用匿名类。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM