重构Java代码
有人能告诉我如何重构下面的代码吗。基本上,我有一个定时器功能,我重复使用。所以我想把计时器放到一个通用函数中重构Java代码,java,Java,有人能告诉我如何重构下面的代码吗。基本上,我有一个定时器功能,我重复使用。所以我想把计时器放到一个通用函数中 import java.util.Timer; import java.util.TimerTask; public class App { private volatile boolean a = false; private volatile boolean b = false; private volatile boolean c = false;
import java.util.Timer;
import java.util.TimerTask;
public class App {
private volatile boolean a = false;
private volatile boolean b = false;
private volatile boolean c = false;
public static void main(String[] args) {
App app = new App();
app.m1();
}
private void m1() {
// m2() should not take more than specified time in timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if(a){
System.out.println("m1 Do nothing");
}
else{
System.out.println("m1 Timeout exception");
}
}
}, 2*60*1000);
a=m2();
System.out.println("Blah");
}
private boolean m2() {
// Killing some time with sleep
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//m3() should not take more than specified time in timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if(b){
System.out.println("m2 Do nothing");
}
else{
System.out.println("m2 Timeout exception");
}
}
}, 1*60*1000);
b = m3();
System.out.println("Blah Blah");
return true;
}
private boolean m3() {
//m4() should not take more than specified time in timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if(c){
System.out.println("m3 Do nothing");
}
else{
System.out.println("m3 Timeout exception");
}
}
}, 20000);
c=m4();
System.out.println("Blah Blah Blah");
return true;
}
private boolean m4() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
谢谢你的帮助。我不是在寻找代码帮助。想知道您对最小化代码的想法。这个问题属于这些计时器之间的区别吗?@Jens我想问题的关键是没有太大区别。@immibis肯定有区别。如果不需要,则不需要3个计时器。@Jens他们检查不同的变量,并打印不同的消息。