我一直想要在我的API中添加调度程序。所以我为此目的设置了一个班级。在这里。
public abstract class SyncScheduler extends Scheduler {
private Thread thread = null;
private boolean repeating = false;
@Override
public synchronized void runTask() {
thread = new Thread(this);
thread.start();
}
@Override
public synchronized void runTaskLater(long delay) {
thread = new Thread(this);
try {
Thread.sleep(delay * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.run();
}
@Override
public synchronized void runRepeatingTask(long period) {
thread = new Thread(this);
repeating = true;
while (!thread.isInterrupted()) {
thread.run();
try {
Thread.sleep(period * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public synchronized void cancel() {
if (thread != null || !repeating) {
throw new SchedulerException("Scheduler is not started or is not a repeating task!");
} else {
thread.interrupt();
repeating = false;
}
}}
Scheduler只实现了Runnable。 问题是每当我尝试创建2个或更多调度程序时,第二个调度程序永远不会启动,直到第一个调度程序完成!例如,如果我在Scheduler上每隔X秒运行一次并且我有另一个取消它,则取消第一个的计划程序永远不会启动!这就是问题所在。
我怎么能并行运行其中两个调度程序?
这些是我的两个测试主要课程。
public class Test {
static Scheduler scheduler = new SyncScheduler() {
@Override
public void run() {
System.out.println("It works.");
}
};
public static void main(String[] args) {
scheduler.runRepeatingTask(1);
new SyncScheduler() {
@Override
public void run() {
System.out.println("Stopped.");
scheduler.cancel();
}
}.runTaskLater(2);
}}
这是第二个。
public class Test {
static Scheduler scheduler = new SyncScheduler() {
@Override
public void run() {
System.out.println("It works.");
new SyncScheduler() {
@Override
public void run() {
System.out.println("Stopped.");
scheduler.cancel();
}
}.runTaskLater(2);
}
};
public static void main(String[] args) {
scheduler.runRepeatingTask(1);
}}
第一个输出"它起作用。"反复,直到我强行停止测试。 第二个给了我"它有效。"一次,然后它给了我"停止。"并与它和例外。
答案 0 :(得分:1)
您错误地使用了线程对象。
要在另一个线程中启动Runnable
对象(在本例中为Thread
对象),该对象必须调用start()
方法。您正在使用run()
方法,该方法只是在同一个线程中调用该方法而不创建新线程。
尝试更改run()
和SyncScheduler.runRepeatingTask
中的SyncScheduler.runTaskLater
。
另外,我刚注意到你的cancel()
方法:
if (thread != null || !repeating) {
throw new SchedulerException("Scheduler is not started or is not a repeating task!");
} else {
thread.interrupt();
repeating = false;
}
如果线程启动,这会使方法抛出异常。我认为它应该是if (thread == null || !repeating) {