我的任务是创建 C# SDK 的 Java 版本。现在。我正在研究一个扩展 C# System.ServiceProcess.ServiceBase 的类,但由于在 Java 中创建 Windows 服务很困难,我专注于该类中的其他一些方法。
我试图在 Java 中复制的当前 C# 方法如下所示
private void StartProcesses()
{
// create a new cancellationtoken souce
_cts = new CancellationTokenSource();
// start the window timer
_windowTimer = new Timer(new TimerCallback(WindowCallback),
_cts.Token, 0, Convert.ToInt64(this.SQSWindow.TotalMilliseconds));
this.IsWindowing = true;
}
在分析这部分代码后,我认为它初始化了一个 System.threading.Timer 对象,该对象每 SQSWindow 毫秒执行一次 WindowCallback 函数。
通读java.util.concurrent文档后位于
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
我不确定如何在 Java 中复制 C# 功能,因为我找不到与 Timer 功能等效的功能。 Java 库提供的 TimeUnit 似乎仅用于线程超时,而不用于发出重复操作。
我也很好奇 CancellationTokenSource 的用途。如果要查询此对象以确定操作是否继续,为什么它不是原始值,例如 boolean 值?它提供了哪些附加功能,Java 的多线程模型中是否有类似的结构?
请您参考如下方法:
使用 ScheduledThreadPoolExecutor,您可以获得非常相似的功能:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = new Runnable() {
public void run() {
//here the code that needs to run periodically
}
};
//run the task every 200 ms from now
Future<?> future = scheduler.scheduleAtFixedRate(task, 0, 200, TimeUnit.MILLISECONDS);
//a bit later, you want to cancel the scheduled task:
future.cancel(true);
