Threading programme


Last Updated:

  1. purnachandrarao

    purnachandrarao Member This Topic's Starter

    Joined:
    Jul 20, 2010
    Messages:
    8
    Likes Received:
    0
    hi
    i want to perform some task for every second of intervals.
    but i am not getting the result for using the Thread.sleep(1000).

    please suggest me how to write programme to full fill this task
     

    Advertisement
  2. Arvesh

    Arvesh Member

    Joined:
    Jan 11, 2012
    Messages:
    6
    Likes Received:
    0
    no answers ! thats sad
     
  3. jiminaus

    jiminaus Well-Known Member

    Joined:
    Oct 27, 2011
    Messages:
    191
    Likes Received:
    36
    Arvesh, why don't you volunteer one then?
     
  4. jaeela

    jaeela Member

    Joined:
    Jan 15, 2012
    Messages:
    9
    Likes Received:
    1
    Thread t = new Thread(new Runnable() {
    public void run() {
    Thread.sleep(1000);
    //Do operations here
    }
    }
    t.start();

    Is this what you want?
     
  5. jiminaus

    jiminaus Well-Known Member

    Joined:
    Oct 27, 2011
    Messages:
    191
    Likes Received:
    36

    In may or may not be important to your application, but be aware that this code suffers from drift. Thread.sleep(1000) will sleep for at least 1 second. It may actually be more by time the thread is actually scheduled for execution.

    And you'll need to catch the InterruptedException thrown by Thread.sleep.


    Another way that doesn't use threads is to use android.os.Handler's postAtTime or postDelayed methods.
     
  6. Lemoncog

    Lemoncog Active Member

    Joined:
    Feb 23, 2011
    Messages:
    26
    Likes Received:
    6
    Check out Timer and Timertask also.
     
  7. JiMMaR

    JiMMaR Well-Known Member

    Joined:
    Jun 12, 2010
    Messages:
    363
    Likes Received:
    57
    As Lemoncog said , use Timer and Timertask
    here's an example

    Code (Text):
    1.  
    2. private Timer timer;
    3. private long delay = 600;
    4. public void start(){
    5. timer.schedule(new Task(), delay);
    6. }
    7. class Task extends TimerTask {
    8.         public void run() {
    9. //your code goes here
    10. timer.schedule(new Task(), delay);
    11.         }
    12. }
    13.  
    I used this for a cool down in my game tutorial, check it out
    https://jimmaru.wordpress.com/2011/12/13/simple-andengine-game-v2-0-more-awesomeness/
     

Share This Page

Loading...