Steady Framerate: Timer vs. Thread

Hey all! Alright, well i belive that the title of this describes what i'm basically looking for. Anyway, i'm writing a simple skateboarding game, and i need a steady framerate. I've tried multiple ways of keeping a steady framerate... all of which failed (obviously) which is why i'm here! ^.^ So yeah, If i already have a thread in my main class would you suggest me making an inner-class that fires a refresh() then waiting a specified number of milliseconds. Or do suggest having a timer that fires a repaint() every certain number of milliseconds. Or maybe there's some sort of custom way to adjust the framerate on different computers, making some sort of custom timer. I appreciate all your inputs! Thanks!

Normally it may be implemented with two threads. The first calculates the scene motion and the second renders and blits the scene to screen. If You are using pure AWT without Swing You need not use repaint. Instead You may render from every thread directly using aquired graphics context. And swing applications must render from event dispatching thread with a component's graphics context. In this case You must use repaint() (called periodically from timer or other thread).

Similar Messages

  • Why is time-critical thread not interrupting sleepless high priority thread?

    Hello,
    I have two threads running in the same execution system on a real-time PXI platform. The time-critical thread sleeps using "AI Single Scan.VI", and acquires my data at a rate of 8000 Hz.
    I have a slower high priority process that calls a DLL function to calculate some filter coefficients. This function call takes longer than 1/8000 s to complete, and runs in a loop, executing as often as it can (with new data from FIFOs).
    I expected the time-critical thread to interrupt the the high priority thread without problem.
    I am finding that unless I insert a LabVIEW delay (for example a wait for x ms VI) in the loop, the real-time system stops responding. With a small delay (ie 1 ms), t
    he acquisition completes, and a FIFO shuts down the loop of the slow process.
    Why do I need a labVIEW delay in the high-priority loop, when the DLL function call itself is quite slow? Even without a DLL call, I would expect the time-critical VI to interrupt, finish its data acquisition, and shut-down the high-priority thread using its FIFO.
    Any suggestions?
    Thanks in advance,
    Frenk

    Here are a couple things to try/check:
    1) Check the call library node in your high priority VI. If it's orange (runs in UI thread), your high priority VI is actually switching to the UI thread every time your dll runs. That alone is not a problem. But if your TC VI tries to update any control terminals, the TC thread will switch over to the UI thread to access UI resources, possibly while the dll within your high priority VI has a lock on those resources. Why does the dll have a lock on UI resources? Because it was running in the UI thread and got interrupted by the TC thread before it finished doing its business. Not likely, but possible.
    2) There's another possible reason you're seeing this behavior. If the TC VI and the high VI call a mutual subVI, the subVI will be elevated to ALWAYS run in the highest priority thread irrespective of the actual caller (in your case, it's the the TC thread). Even when the *high priority VI* calls the mutual subVI, that subVI runs in the time-critical thread, which means there's a thread switch from high to TC, then back to high after the subVI finishes. And because high and TC VIs are in the same exec system, that mutual subVI will always run in the 1 and only TC thread alotted to that exec system.
    So, while your TC VI is running, you're in the TC thread. While, your high VI is running, you're in a high non-TC thread, and when your high VI calls the mutual subVI, you're again in the TC thread until the subVI finishes.
    So how could this arrangement cause your TC VI to become starved by the high VI? If your TC VI wakes up while the high VI is in the middle of running the mutual subVI, the TC thread responsible for running the TC VI is actually busy (in the middle of running the subVI in your high VI!!!), so the TC thread cannot run your TC VI until it finishes running that mutual subVI.
    The fix: make your TC VI run in a different exec system. It will be given its own TC thread that no one else can mess with. When TC VI wakes up, it's guaranteed a TC thread.
    I think there's a good reason behind why a mutual subVI ALWAYs runs at the highest priority of all its callers, irrespective of the actual caller's priority...but I can't think of the reason at the moment.

  • To display splash screen for certian period of time using threads

    i want to write a program to display splash screen for certian period of time using threads. could some one help me

    If you just want a splash screen: [http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/splashscreen/|http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/splashscreen/]
    If you want to learn threads: [http://java.sun.com/docs/books/tutorial/essential/concurrency/|http://java.sun.com/docs/books/tutorial/essential/concurrency/]

  • Joining a Timer started thread

    Given a piece of code that uses a Timer to start a TimerTask, can the main thread get at the timer-started Thread so it can join() on it?

    thrice wrote:
    kajbj wrote:
    @Op.
    Why did you create a new Thread? Um, I'm not sure if you mean "thread" as in a new thread of Java code, or "thread" as in new topic on this forum!I meant thread as in topic.
    >
    I created new threads in my Java code because I need to get about 50 separate pieces of work done as concurrently as the hardware will allow, while still letting the main thread get work done.
    I created a separate topic in this forum because this is a specific question to which I'd like a specific answer!
    @All others. Please continue the discussion in the new thread [http://forums.sun.com/thread.jspa?threadID=5344116]
    Um, no, please answer this simple question in this thread! I don't know if join()ing to a Timer-started Thread object is the way to solve my overall problem. I suspect it isn't, and your suggestion to use a CountDownLatch reinforces that suspicion.A Timer is single threaded. It will not start 50 threads even if you have 50 timer tasks.
    >
    For my Java education, I'd like to know if I can join() to a Timer-started thread, and if so, how do I do it?See above.

  • Timer or thread

    public boolean validateUser() throws Exception {
    userDao = new EbrUserDAO();
    try {
    ldapDao = new LdapDAO();
    ldapDao.validateUser(this);
    DesEncrypter enc = new DesEncrypter("too many secrets");
    this.setPassword(enc.encrypt(this.password));
    this.setType("I");
    log.info("Attempting to save user attributes");
    userDao.saveEbrUser(this);
    return true;
    } catch (LoginException e) {
    DesEncrypter enc = new DesEncrypter("too many secrets");
    this.setPassword(enc.encrypt(this.password));
    log.info("[UserDAO] Attempting to validate user : " + this.getUserId());
    return userDao.validateEbrUser(this);
    Hi!
    I have a problrm here... i want only the try part to execute in just 1 min. after it exceeds the alloted time i'll force the try part to throw exception then continue with the succeeding statements.
    how can i do that? should i use timer or thread?
    thanks in advance!
    pao

    pao wrote:
    public boolean validateUser() throws Exception {
    userDao = new EbrUserDAO();
    try {
    ldapDao = new LdapDAO();
    ldapDao.validateUser(this);
    DesEncrypter enc = new DesEncrypter("too many secrets");
    this.setPassword(enc.encrypt(this.password));
    this.setType("I");
    log.info("Attempting to save user attributes");
    userDao.saveEbrUser(this);
    return true;
    } catch (LoginException e) {
    DesEncrypter enc = new DesEncrypter("too many secrets");
    this.setPassword(enc.encrypt(this.password));
    log.info("[UserDAO] Attempting to validate user : " + this.getUserId());
    return userDao.validateEbrUser(this);
    Hi!
    I have a problrm here... i want only the try part to execute in just 1 min. after it exceeds the alloted time i'll force the try part to throw exception then continue with the succeeding statements.
    how can i do that? should i use timer or thread?
    thanks in advance!
    paowhat u r trying to achieve ?? please explain >>

  • Timer vs Thread in SessionBean

    Hi,
    I'm having a web service MyWebService which is having a stateless session bean which will invoke a task T1 and soon after starts poll the database after every five seconds to fetch the report of task T1. To wait for that 5 seconds i have two ways.
    1) I'll get the current thread of the bean and call the sleep method. i.e.
    Thread.getCurrentThread.sleep(5000);2) I'll use Timer class i.e
    import java.util.Timer;
    public class TimerTest {
    TimerTest(){}
    public static void main(String args[]){
    Object sync = new Object();
    ResponseTimer responseTimer = new ResponseTimer(sync, timeOut, polDuration);
    responseTimer.cancel();
    static long polDuration = 5000;
    class ResponseTimer extends Timer{
    ResponseTimer(){...}
    public String getResopnse(){
    synchronized(sync){
    while(...){
    try{
    sync.wait(polDuration);
    //POLL DATABASE
    }catch(InterruptedException intrruptedException){...}
    return "Success";
    }Can anyone tell me which is the best way to go for and with how it'll be handled by container?

    If i'll not use Timer or Thread, then what is the way to wait for 5 seconds. My requirement is
    SessionBean is having synchronous call. Once it initiates the task T1, it has to immediately start fetching report of T1 from the database. If report is not present, wait for 5 seconds, again check for the report from database.
    How do i implement the waiting logic inside my bean?

  • Timer in thread.

    Plz,How to make an thread that starts a timer but if a message came from a client that timer stops .
    how to make the function that recieve the messgae stop the timer.
    thnx.
    <the function recieves a udp packet from a client or whatever>.

    Hi,
    Read the documentation. A Timer tasks a TimerTask, and the TimerTask has a cancel method.
    http://java.sun.com/j2se/1.4.2/docs/api/index.html
    /Kaj

  • How to set the running time of Thread??

    Hello all
    i am new and fresh student to learn Java.
    i want to set a limit time to run a thread.

    public void interrupt()
    Interrupts this thread.
    First the checkAccess method of this thread is invoked, which may cause a SecurityException to be thrown.
    If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
    If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.
    If this thread is blocked in a Selector then the thread's interrupt status will be set and it will return immediately from the selection operation, possibly with a non-zero value, just as if the selector's wakeup method were invoked.
    If none of the previous conditions hold then this thread's interrupt status will be set.
    Throws:
    SecurityException - if the current thread cannot modify this thread
    to quote the api
    but in your case Aldaris it would have no effect
    but if you wrote the code as..public void run(){
    while(!interrupted()){
      System.out.println("Pete_The_Hat");
    }then it would break the loop :-)

  • Advantages and disadvantages among Timer, ScheduledExecutorService, Thread

    Hi, what are the exact advantages and disadvantages among using Timer, using ScheduledExecutorService and just using Thread (Thread.sleep(...))?
    For the simple task which needs to poll some values by some interval (the interval is not supposed very accurate, maybe about 5 seconds just ok), is it ok for just using Thread, like:
    run() {
      while(isRunning) {
         Thread.sleep(5000);
         //do something
    }?

    jiangyc wrote:
    Why using Timer and TimerTask is simpler and better than using Thread directly? Because it handles the rote stuff that's not directly part of your application. Ideally, your code should just be the marginal stuff that's specific to your app; anything else should be in the library you use. The less code the better.
    I feel just using Thread doesn't make my code hard to maintain and by far I don't find any performance issue raised by using Thread (in our swing application, there are maybe less than 10 Thread objects which take care of the different polling tasks). It's not a performance issue; it's a code management issue. (Although the chances are good that Timer will have been well-tuned.) The less code you have, the less code you have to wade through to fix bugs, make changes, etc. This might not seem like much when it's a small program, but it adds up. In a business environment where you have huge codebases worked on by dozens of people (many of whom don't work there anymore) it becomes really important to only write what you have to and no more. Maybe if you're doing a small project it's not important, but keeping your code clean a good habit to get into.
    And I wonder the base implementation of Timer and TimerTask is not using Thread?Of course it is. That's not the point. The point is that it keeps your code cleaner.
    When you use Thread directly, probably the only part that's directly relevant to your program (as opposed to any other program that uses Thread) is the value you're sticking in Thread.sleep() -- the delay. You specify that in the schedule() call to the Timer.
    If you keep your use of Thread minimal, then it might not be much bigger than using Timer/TimerTask, but the latter does more, including stuff you'll probably need to add (like ways to cancel the task).
    Also, when you do this using Thread, you're exposing the implementation, but when you use Timer.schedule, you're exposing the intent. The latter makes for clearer code.

  • Thread CPU time: does it include the time while thread is waiting

    Hi,
    My question is regarding the getCurrentThreadCpuTime() supported by the ThreadMXBean.
    I wonder if the returned time includes the time while the thread is waiting, i.e. after the thread calls wait() and before getting a notify() or a notifyAll().
    Thanks,
    Nuha

    CPU time is intended to reflect actual time executing on a CPU. If block for a lock/wait/sleep or other blocking operation like I/O then you don't consume CPU while blocked.
    On Solaris it is implemented using gethrvtime()
    If a VM used a busy-wait for something rather than blocking (not likely with wait()) then that's consuming CPU time.

  • Timer or Threads?

    Hi,
    I'm making some sort of forum where when
    a user posted, there will be a "NEW" word
    beside the post, just to indicate that its a
    recent post.
    So after some time, the "NEW" will disappear,
    and what I would like to know is can
    I use a Timer and TimerTask alone to do the job?
    Or should I use Threads?
    Any suggestions to help me get started are
    welcome. Thanks.

    Thanks for the quick reply.
    Ok, so if I created a Timer, does it mean that
    each TimerTask will act on its own?
    For example, I have this script:
    public static void setTime(String s, int t)
    final Timer timer = new Timer();
    final String name = s;
    final long waitTime = t * 1000;
    timer.schedule(new TimerTask()
    public void run()
    System.out.print(name);
    System.out.print(this.cancel());
    }, waitTime);
    Will the values be overidden when i call setTime
    next time?
    Thanks.

  • Accurately Calculating the time a Thread takes to run

    How do I accurately gain timings for a thread? I have a number of threads which are calling CalculatorEngine which locks on an object starts a timer (ctime = System.currentTimeMillis();) and then logs the time just before the thread exits
    System.out.println("Calculations for " + setName + " for " + calcsMadeByCalcEnginge + " positions took: " + (System.currentTimeMillis() - ctime));
    But if there is a context swich my timer will continue to run until the thread is reactivated and then completes... How can I gain the actual timings for how long the thread took?

    How do I accurately gain timings for a thread? You can't.
    >
    But if there is a context swich my timer will
    continue to run until the thread is reactivated and
    then completes... Correct.
    How can I gain the actual timings
    for how long the thread took?You can't. As I said and as you already pointed out why.
    Not to mention that on modern OSes threads in other apps might steal time as well.
    You can just run it in a loop, make sure no other resource hungry apps are running and then estimate the time taken.

  • Which structure to use for time-restricted thread pools

    Hi,
    I am looking for the advice on the best concurrent structure (if such even exist)
    for executing concurrent jobs and forcing the timeout on these.
    Here is the problem description:
    I have to call up to 50 webs services.
    I want to run these web service calls concurrently (i.e. in separate threads)
    I want to force timeout, or execution windows of each one of these threads.
    E.g. I want to make sure that each threads completes the execution in 5 sec
    regardless if the web service result has returned or not.
    Is there a combination of the pool and a worker type from java.util.concurrent
    or elsewhere that would allow me to implement this functionality.
    Thank you in advance,
    Edmon

    Do you want get rich easily?
    You can change life, you can have money as much as you want. All you have to do is to send 12 dollars to 6 people bank accounts.
    All you have to do is the fallowing:
    You have to have bank account. You have to send 2 $ to below listed bank accounts. This is legal, you made a favour for those people and for your self.
    This is the bank accounts:
    1. LT957300010074515201
    2. LT217044000017612013
    3. LT547400012388523830
    4. LT857044000879616105
    5. LT577300010085485906
    6. LT837300010088377105
    After sending money, you need to delete the first bank account and make room for your account, after deleting first account, in the bottom of the list write your accounts number. You have to delete only the first one. Very important to do it honestly.

  • Application threads were stopped for a long time

    Hi, We have got the following problem.
    application threads were stopped for a long time after Minor GC hava finished. Minor GC takes usally less than 1sec but a time application threads were stopped tekes often 100 sec.
    What's jvm doing then? alternatively we want to get more information when Minor GC occured.
    gc.log
    33919.643: [GC 33919.643: [ParNew: 376030K->102916K(546176K), 0.1462336 secs] 1953320K->1680371K(4642176K), 0.1465861 secs]
    Total time for which application threads were stopped: 0.1557298 seconds
    Application time: 1.3021807 seconds
    34020.827: [GC 34020.827: [ParNew: 376068K->103166K(546176K), 0.3350141 secs] 1953523K->1681429K(4642176K), 0.3353194 secs]
    Total time for which application threads were stopped: 100.0714587 seconds
    Application time: 1.0932169 seconds
    34121.180: [GC 34121.180: [ParNew: 376318K->100333K(546176K), 0.3740967 secs] 1954581K->1680438K(4642176K), 0.3744228 secs]
    Total time for which application threads were stopped: 99.2983213 seconds
    Application time: 0.7258378 seconds
    34122.304: [GC 34122.305: [ParNew: 373485K->115425K(546176K), 0.9584334 secs] 1953590K->1696193K(4642176K), 0.9587701 secs]
    Total time for which application threads were stopped: 0.9823952 seconds
    machine spec and jvm option
    T2000 Solaris10 Sparc
    1cpu 8core 32thread 1GHz, 8GB Memory
    jvm 1.4.2_14
    -d64 -server
    -XX:NewSize=800m -XX:MaxNewSize=800m
    -XX:SurvivorRatio=1
    -XX:+DisableExplicitGC
    -XX:+UseConcMarkSweepGC
    -XX:+UseParNewGC
    -XX:+CMSParallelRemarkEnabled
    -XX:MaxPermSize=256m -XX:PermSize=256m
    -XX:+UsePerfData
    -verbose:gc
    -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
    -XX:+PrintTenuringDistribution
    -XX:+PrintGCApplicationStoppedTime
    -XX:+PrintGCApplicationConcurrentTime
    -Xloggc:/opt/local/jj/jboss/server/fujiyama/log/gc.log
    -Xmx4800M -Xms4800M
    we attempt single thread GC or set 2400M for heap memory
    or -XX:UseParallelGC or set the following param
    -XX:NewSize=1000m -XX:MaxNewSize=1000m
    -XX:SurvivorRatio=6
    -XX:TargetSurvivorRatio=80
    -XX:MaxTenuringThreshold=20
    -Xmx4000M -Xms4000M
    but the situation wasn't improved.

    Hi Thanigaivel
    the above flag reports all the stop the world pauses not only
    those caused because of gc. Unfortunately, this flag has
    misleading name. Thanks for your info!!
    Can you think of any reasons other than GC that cause the stop the world pauses? How can I identify the reason? Are there any VM options to log all the activities that causes the "stop the world" pauses?

  • How do i use multiple threads( very much real time), using JavaFX?

    I'm creating an application, using JavaFX because one can create awesome GUI using JavaFX. I need to know how to create real time multiple threads using javafx.
    JavaFX doesn't support creation of multiple threads, but i think there is another way of doing it. I need it work in real time as my application works with an hardware (wacom intous 3 tablet), and i need mutiple threads to get all the parameters from the stylus of the tablet simultaneously...
    any code which will help me out or explaination on how to go about this is appreciated...
    Help required quickly...

    See example at
    [http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/|http://jfxstudio.wordpress.com/2009/06/09/asynchronous-operations-in-javafx/]

Maybe you are looking for