问题
Like below link, is there java function that thread interrupt asynchronous queue and put in alertable?
https://docs.microsoft.com/en-us/windows/desktop/sync/using-a-waitable-timer-with-an-asynchronous-procedure-call
I want to make async timer function in java. I checked it works in c++. But I don't know if it is in java. When main thread run and check periodically if there are the async timer fired and run it and going back and run again. That is what i want to do. Of course, when checking async timer fired, I will use sleep with alertable.
I've tried to find it in google, but I didn't find. Thanks in advance!
What I want to do more detail is below.
Let's assume that there is a program that getting requests like :
msg1 : msgname=aa1 to=sub1 waittime=1000 msgbody
msg2 : msgname=aa2 to=sub2 waittime=2000 msgbody
msg3 : msgname=aa3 to=sub1 waittime=3000 msgbody
msg4 : msgname=aa3 to=sub1 msgbody . .
and the program should pass each msg to sub1, sub2 described in msg's to field.
If waittime exists, it should pass the message as much as waittime millisec later. the program should do that in 1 thread, and there over 10 thousands msg in one second. If use just synchronous sleep, all msgs souldn't pass in a time and delayed. I check it works well in c++ code, and I have seen a commercial program made in java(maybe) does this. But I am novice in java and I want to know it is possible in java.
回答1:
Java doesn't have concepts analogous to Windows' "alertable" and the APC queue, and I doubt that it would be possible to both use the Windows native APIs and integrate this with normal Java thread behavior.
The simple way to implement timers in Java is to use the standard Timer
class; see the javadoc. If this isn't going to work for you, please explain your problem in more detail.
In response to your followup problem: yes it is possible in Java. In fact. there are probably many ways to do it. But Timer
and TimerTask
are a good a way as any. Something like this:
public class MyTask extends TimerTask {
private String msg;
private String to;
public Mytask(String msg, String to) {
this.msg = msg;
this.to = to;
}
public void run() {
// process message
}
}
Timer timer = new Timer();
while (...) {
// read message
timer.schedule(new MyTask(msg, to), waitTime);
}
来源:https://stackoverflow.com/questions/53787825/is-there-java-thread-interrupt-asynchronous-queue-and-put-in-alertable