我有一個定期執行代碼的線程, G。每10秒鐘一次。我希望可以選擇以自發方式調用相同的代碼,而不必等待10秒鐘。但是自動執行和自發執行的代碼不能同時運行,如果用戶在調用相同方法時按下執行按鈕,它們應該按順序運行。在週期性運行的線程中自動執行代碼
有沒有人知道一個好的模式,甚至可以解決這種需求的類?
首先想到的是使工作方法同步。但是在這種情況下,手動執行(例如按下按鈕)被阻塞,並且必須等待直到線程中的方法結束。有沒有更好的方法沒有阻塞?
實施例:
public class Executor extends Thread {
// endless loop, executes work method periodically with pause inbetween
@Override
public void run() {
while(true) {
work("automatic");
pause(10000);
}
}
// Working method that's executed periodically or manually
private synchronized void work(String text) {
System.out.println("Working " + text + " " + System.currentTimeMillis());
}
// helper method that pauses the thread
private static void pause(long sleepMs) {
try {
Thread.sleep(sleepMs);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// start automatic execution
Executor executor = new Executor();
executor.start();
// pause a while
pause(1000);
// manual execution
executor.work("manual");
}
}
編輯:解我的要求:
public class ScheduledExecutor {
public static void main(String[] args) throws InterruptedException {
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
executor.scheduleWithFixedDelay(new Work("auto"), 0, 10, TimeUnit.SECONDS);
Thread.sleep(1000);
executor.execute(new Work("manual"));
}
public static class Work implements Runnable {
String text;
public Work(String text) {
this.text = text;
}
@Override
public void run() {
System.out.println("Working " + text + " " + System.currentTimeMillis());
}
}
}
中斷睡眠? –
如果線程在非休眠模式下被中斷會發生什麼? – Roland
您是否可以更新您的問題以清楚說明您希望如何工作。你說你不希望手動和自動的線程代碼同時運行。然後你說你不想在按下按鈕時手動執行被阻止...... – Allan