Java Event Generation -
i want design scheme generate specific event @ constant rate , go on doing in background. in foreground give output of other events if want. background event not stop. best way accomplish in java?
this definition of threading , needs come level of understanding.
on simplest level, create thread sleeps amount of time executes code. there lots of other ways it, few shorter overriding run method of thread.
if want more abstract, through concurrent bundle in java docs, there many methods want, , java.util.timer 1 @ well.
be aware of variables , collections might accessed different threads @ same time. aware if have gui shuold not update gui new thread.
edit add together non-thread solution
(i don't think want, in comments asked non-threaded solution).
if wish without threads (meaning wish in current thread) have "interrupt" current thread check see if other task needs process. first need method this:
long lastrun=system.currenttimeinmillis(); final long howoftentorun=60*1000 // every min testforbackgroundtask() { if(lastrun + howoftentorun < system.currenttimeinmillis()) { // drift, if don't want drift utilize lastrun+=howoftentorun lastrun=system.currenttimeinmillis() // occasional task is. // task in-line here of course of study violate srp runbackgroundtask() } }
after that, need sprinkle testforbackgroundtask throughout code:
lotsofstuff.... testforbackgroundtask() longmethod() testforbackgroundtask() morestuff... testforbackgroundtask() ...
note if longmethod() takes long time need set calls testforbackgroundtask() within well.
i know ugly, , uglyness of solution why threads used. advantage absolutely prevent threading conflicts.
the other single threaded solution--making code event driven--is harder , impacts code (there build called finite state engine made purpose).
java
No comments:
Post a Comment