我一直想要很長一段時間來添加調度器到我的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;
}
}}
調度器只是實現了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);
}}
第一個輸出「It works。」。一直到我強制停止測試。 第二個給我「它的作品。」一次,然後它給了我「停止」。並與它和例外。
需要更多信息。向我們展示您的主要課程和調度程序。 – waltersu
如果要同時運行2個「事物」,請使用多線程 – ScriptKiddy
如果要同時運行兩個*線程*,則可能必須使用倒計數鎖存器http://docs.oracle.com/javase/ 7/docs/api/java/util/concurrent/CountDownLatch.html在一個地方停止兩個線程,然後一起運行。 –