2016-06-12 55 views
0

我一直想要很長一段時間來添加調度器到我的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。」。一直到我強制停止測試。 第二個給我「它的作品。」一次,然後它給了我「停止」。並與它和例外。

+0

需要更多信息。向我們展示您的主要課程和調度程序。 – waltersu

+0

如果要同時運行2個「事物」,請使用多線程 – ScriptKiddy

+0

如果要同時運行兩個*線程*,則可能必須使用倒計數鎖存器http://docs.oracle.com/javase/ 7/docs/api/java/util/concurrent/CountDownLatch.html在一個地方停止兩個線程,然後一起運行。 –

回答

1

您正在錯誤地使用線程對象。 要在另一個線程中啓動Runnable對象(在本例中爲Thread對象),該對象必須調用start()方法。您正在使用run()方法,它只是在不創建新線程的情況下在同一線程中調用該方法。

嘗試在SyncScheduler.runRepeatingTaskSyncScheduler.runTaskLater之間更改run()

另外,我只注意到你的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) {

+0

沒有工作... – Nick

+0

@Nick你確定你的取消方法有合適的條件嗎? – dieend

+0

嗯,我沒有看到,謝謝!但我認爲這不會有所作爲。 – Nick

相關問題