我需要检查我的Java应用程序中是否存在智能卡,以生成类似"事件"关于智能卡的移除。
我有一个简单的方法来测试它:
public boolean isCardIn(){};
对此进行推广的最佳方式是什么?
在这种情况下,我应该使用java.utils.Timer.Timer()
还是ExecutorService()
?
这是我目前的实施:
开始投票
checkTimer.schedule(new CheckCard(), delay,delay);
这是计时器的执行:
private class CheckCard extends TimerTask{
@Override
public void run() {
try{
if(!SmartcardApi.isCardIn(slot)){
// fire event
}
}catch(Exception e){
}
}
}
答案 0 :(得分:0)
我再看一下StackOverflow,因为我认为你的问题得到了回答: Java Timer vs ExecutorService?
我认为通常,使用较新的API会更好,在这种情况下是ExecutorService
。以下是我的表现:
public static void main(String[] args) throws InterruptedException, ExecutionException {
ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
SmartCardApi smartCardApi = new SmartCardApi();
// Polling job.
Runnable job = new Runnable() {
@Override
public void run() {
System.out.println("Is card in slot? " + smartCardApi.isCardInSlot());
}
};
// Schedule the check every second.
scheduledExecutor.scheduleAtFixedRate(job, 1000, 1000, TimeUnit.MILLISECONDS);
// After 3.5 seconds, insert the card using the API.
Thread.sleep(3500);
smartCardApi.insert(1);
// After 4 seconds, eject the card using the API.
Thread.sleep(4000);
smartCardApi.eject();
// Shutdown polling job.
scheduledExecutor.shutdown();
// Verify card status.
System.out.println("Program is exiting. Is card still in slot? " + smartCardApi.isCardInSlot());
}
package test;
import java.util.concurrent.atomic.AtomicBoolean;
public class SmartCardApi {
private AtomicBoolean inSlot = new AtomicBoolean(false);
public boolean isCardInSlot() {
return inSlot.get();
}
public void insert(int slot) {
System.out.println("Inserted into " + slot);
inSlot.set(true);
}
public void eject() {
System.out.println("Ejected card.");
inSlot.set(false);
}
}
Is card in slot? false
Is card in slot? false
Is card in slot? false
Inserted into 1
Is card in slot? true
Is card in slot? true
Is card in slot? true
Is card in slot? true
Ejected card.
Program is exiting. Is card still in slot? false
在这种情况下,我使用了一个简单的Runnable
,它可以调用另一个对象来触发其event
。您也可以使用FutureTask
代替此Runnable
,但这只是基于您希望此事件被解雇的 的偏好..