java通过当前线程调用多个方法
假设我们有这些类并阅读注释
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
}
}
此外,我不想使用构造函数来确定是否要同时调用这两个方法
# 1 楼答案
您可以尝试将线程池与单个线程一起使用,并根据需要让方法排队:
这样,这两个方法将由同一个线程按顺序执行,但会分别执行
# 2 楼答案
你可以使用匿名类
# 3 楼答案
将参数添加到类
MyRunnable
。将此参数称为“runingMode”。它可能是一个枚举:现在你的类
MyRunnable
应该有一个模式列表:实现
run()
方法如下:创建类的实例,并将当前需要的模式传递给它: