Game main loop using Thread. How to ?

Hello !
Is anybody know what happened with threads, which was created by MIDLet when MIDLet will be closed ?
More details: i design a specific game engine for MIDP2.0. In many available resources main game loop implemented through separate Thread, but one thing is just missed - how to correctly stop this thread when player want to exit from game ? Mostly all examples just call notifyDestroyed() and do nothing more. But I think what it is wrong program behaviour. So I have questions to advanced MIDP programmers:
1) Do we need correctly stop all Threads before call notifyDestroyed() or can just forget about it ? (I think need to stop all threads ...). Maybe some documentation or usefull link is available about this or related problem ?
Where get documentation about Threads in Java, and how to VM stop thread during garbage collection. As I think exactly GС will destroy MEDLet threads if I don't stop it manually ?

... But I think that all created threads should be
killed in logical right place. For example, if thread
is using for animation and created in Canvas object,
this thread should be killed before killing Canvas
object (for example command "Exit" have been choosen,
firstly we kill thread, secondly we call destroyApp )
If midlet uses user interface, I never called
notifyDestroyed() from my own created thread, because
application usually should be finished when command is
choosen or some key pressed.I completely agree with both notes, and even think what I was wrong in general - when decide to use main loop paradigm in PC way (strictly speaking I just copy paradigm from PC project). You give me an good idea - use custom-purpose threads instead general-purpose "main-loop" thread. I just will look on this thread from other point of view and use it only for call update() for my canvas and provide way to handle time-depended actions (say for animation). No anything more. So all I will need - proper synchronization when perform time-depended action.
So I can stop that thread from destroyApp() when AMS want to destroy my MIDlet, and I can stop that thread from any event-handler in my canvas (in command handler or just key-pressing handler) and then call notifyDestroyed() in order to stop MIDLet manually. So no more calling notifyDestroyed() from any MIDlet-own threads. What you think ?
Just for intresting - citation from JVM Specification:
2.16.9 Virtual Machine Exit
A Java Virtual Machine terminates all its activity and exits when one of two things happens:
* All the threads that are not daemon threads (�2.17) terminate.
In CLDC specification no any changes in this paragraph was made, so we can say what if we does not stop all threads which we create in MIDlet the MIDLet execution will be endless ? It is intresting - implementation JVM in real device start JVM for each MIDLet or start JVM once and start MIDlets in this one-session JVM ? In first-case it is possible to just stop JVM (with all threads) and release any resources (looks little dirty, but why not ?) in second-case all "zombie" threads can live endless (until device switch off) and just decrease performance and eat resources ...
Need more specification ...
Many thanks to RussianDonz for collaboration.

Similar Messages

  • Game loop using Swing?

    Hey everyone. My simple game engine currently uses Swing for the frames and components, but uses an AWT Canvas for the actual game display. I'm trying to figure out how to change entirely to Swing components.
    Here's basically how I've laid out my game loop thread using Canvas:
    1. Do calculations since last loop
    2. Get Graphics2D object via the canvas' BufferStrategy object
    3. Clear the background with white.
    4. Call the draw(Graphics2D) method.
    5. Dispose & flip the buffer.
    6. Call the update(long) method using the calculations from step 1.
    7. Sleep for a bit.
    8. Repeat loopThis is working very smoothly right now and is very flexible for subclassing. But since it's a mix of Swing & AWT there are some problems here and there and I feel it could be improved by keeping it Swing-only.
    What's the best way to implement a similar game thread loop using a Swing component?
    Code can be supplied if needed. Thanks!

    Use a JPanel instead of a Canvas.

  • How to use Thread

    Hi,
    I am trying to write a program that does a background process. The process is controlled by two buttons: Start and Stop. I thought I'd use threads, but it does not work; the start button remains depressed and the user cannot click on the Stop button. The line calling run() is executed and execution transfers to the run method in my Thread subclass, which is wrapped in an infinite loop. The line after the run() method is never reached. It is as if it is not creating an extra thread at all.
    I have written something basic which is similar, the same problem occurs with this code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class CounterFrame extends JFrame {
        private JPanel pnButtons;
        private JButton btStart;
        private JButton btStop; 
        private ThreadTester threadtester;
        public CounterFrame() {
            pnButtons = new JPanel();
            btStart = new JButton("Start");
            btStop = new JButton("Stop");
            btStart.addActionListener(new StartListener());
            btStop.addActionListener(new StopListener());   
            pnButtons.add(btStart);
            pnButtons.add(btStop);
            add(pnButtons);
            pack();
            threadtester = new ThreadTester();
        private class StartListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                threadtester.run();
        private class StopListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                try {
                    threadtester.sleep(Long.MAX_VALUE);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
        private class ThreadTester extends Thread {
            int counter;
            public ThreadTester() {
                counter = 0;
            public void run() {
                while(true) {
                    System.out.println(counter);
                    counter++;
                    try {
                        sleep(1000);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    yield();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new CounterFrame().setVisible(true);
    }Can anyone advise where I am going wrong, please?

    Please run, don't walk to the article on the Sun site (you can search for it) entitled Concurrency and Swing (or something similar). Problems I see include:
    1) Don't call run on a thread as that will just "run" the run method and not create a background thread. Instead you call "start".
    2) Don't call Thread.sleep() on the EDT or the Event Dispatch Thread. This is the single thread that Swing uses to draw components and to interact with the user. Calling Thread.sleep on it will put your whole program to sleep which is not what you want.
    3) Consider using a Swing Worker, or better still a Swing Timer.
    Again, read the article and you will understand this better.

  • How to use thread to monitor a file

    Hi
    I have a situation where i want to monitor a file while current java process is running, for example
    The process would be like below,i have to do it using Java 1.4
    1 Start Main Java Class
    2 Start Another thread to monitor a file, from this main Java Class
    3 Return control back to main java class to do future processing
    4 When the process in this class is done, kill the monitor process.
    5 If the file is modified by external process, do some processing in the thread,
    What i did was as below, the main java class
    Thread t = new Thread(new TestOptimizationThreadWorker());
    t.run();
    // continue doing the process
    t.stop();the other thread class is as below
    public class TestOptimizationThreadWorker implements Runnable
         public void run()
              // monitor the external file here
    }But some how the control does not come back to main program after i run the thread,
    Any suggestions
    Ashish
    Edited by: kulkarni_ash on Sep 26, 2007 10:06 AM
    Edited by: kulkarni_ash on Sep 26, 2007 10:53 AM

    Hi
    Yes after changing, t.run() to t.start(), it works, but what are the issues you see,
    i have attached the whole code below
    Java Main Class
    public class TestOptimizationThread
         public TestOptimizationThread()
         public String doMessage()
              TestOptimizationThreadWorker tt =     new TestOptimizationThreadWorker();
              Thread t = new Thread(tt);
              System.out.println ("In Do message");
              try
                   System.out.println ("Before starting thread");
                   t.start();
                   System.out.println ("After starting thread");
              catch(Exception exc)
              finally
                   System.out.println ("in finally");
                   tt.changeB();
              return "";
         public static void main(String args[])
             new TestOptimizationThread().doMessage();
    }Java Thread class
    public class TestOptimizationThreadWorker implements Runnable
         private boolean b = true;
         public TestOptimizationThreadWorker()
              System.out.println ("Creating this class ");     
         public void run()
              System.out.println ("In Run Method");
              int i =0;
              while(b)
                   System.out.println ("int "+ i);     
                   i++;
         public void changeB()
              b = false;     
    }Ashish

  • How to create a multiplayer game for steam using flash/flex?

    Hi guys,
    We've got a multiplayer game ready to go. Currently it is not multiplayer, but we'd like to get it to a stage where it can be played over the steam network by users of steam and owners of steam games.
    We'd like to if anyone could briefly give us a breakdown of how to get out game up on steam and available for multiplayer?
    Does steam host servers, and can we utilise a steam server to transfer data between players or would we have to run our own server?
    Currently were using flash builder to publish via adobe air to a windows desktop exe. Can anyone briefly explain how - once a player has downloaded the game from steam we can connect two players? Does anyone know how to use actionscript 3 to access steam network?
    Anyone have any experience developing multiplayer turn based game for steam using flash /actionscript 3 /adobe air?
    Thanks for your help in advance,
    i

    You would want to use the SteamWorks API, which is available from Steam as a C++ library, but there is most likely an Adobe Native Extension (ANE) that would allow you to use the library in AS3.
    I've never used SteamWorks but it seems to support peer-2-peer matchmaking (in other words, you wouldn't even need your own server, I think.)
    SteamWorks API:
    https://partner.steamgames.com/documentation/api
    Search results for "SteamWorks AIR ANE":
    https://www.google.com/search?q=steamworks+air+ane
    -Aaron

  • MASTER/SLAVE PATTERN: how to stop slave loop without stop main loop

    Hi All, I am studying the master/slave loop and saw an examples are like this (only master block shows)
    From this case, as I understand, if we click "set" button, slave loop will run. If we click this button again to mak it "Flase", the slave loop will be stopped as well as the main loop will be stopped as well.
    Now if I have a multi-function main loop, I just want to start or stop slave loop when click "set" button, how can I do it? Thank you very much! 

    bhl3302 wrote:
    From this case, as I understand, if we click "set" button, slave loop will run. If we click this button again to mak it "Flase", the slave loop will be stopped as well as the main loop will be stopped as well.
    Your understanding is completely wrong.  There is nothing in the image you show that would stop either loop.  In this situation the "set" button would normally have a latching mechanical action, meaning that when it is pushed, it will stay true until it is read once, at which point it will return to false.  Placing the control terminal inside the event case causes the terminal to be read and resets the button to false.  With a latching mechanical action, there will be only one event generated even though the boolean will change value twice (from false to true, and from true to false).  You'll never have a situation where you push the button once to set it true, and again to set it false.  However, even if the mechanical action is switching, not latching, it still won't make a difference here - the event case does the same thing whenever the value changes, regardless of whether it's true or false.

  • The Ipod I have been using for years no longer will hold a charge. My wife doesn't use hers so I would like to use it as my main ipod now. How do I get it to sync my play lists?

    The Ipod I have been using for years no longer will hold a charge. My wife doesn't use hers so I would like to use it as my main ipod now. How do I get it to sync my play lists?

    Hi BFW29,
    Thanks for visiting Apple Support Communities.
    You can use these steps in this article to set up syncing with your computer and the new iPod:
    iTunes 11 for Windows: Set up syncing for iPod, iPhone, or iPad
    http://support.apple.com/kb/PH12313
    Regards,
    Jeremy

  • How to use threads in JSP???

    hello
    i want to use threads with JSP.
    i want to write a jsp page which will
    start 2 different threads. the 1st thread should just display a message and the second page should redirect this page to another jsp page.
    till the redirection is goin on, the message should be displayed in the browser from the 1st thread.
    i dont know actually how to use threads in JSP by implementing the Runnable insterface, if not m then how do i do it ??
    thanx
    Kamal Jai

    Why do you want to use threads to do this ??
    If you write a message and do a redirection, the message will be displayed until the other page will be loaded into the browser...
    I already launched a thread from a JSP but it was for a four hour process where the user can close his browser windows.

  • How to use thread only for progress bar.....

    Hello,
    I am working on an application which is taking time to load. Now I want to use a progress bar to tell the user of the application that It is taking time to load. How to do it... I read the Java swing tutorial and went through the example. Please tell me what to do. Because I am unfamiliar with Threads and I am not using thread anywhere in my application.

    You are using threads. All Java execution occurs on threads. Write a Java GUI and you're in a multithreaded environment - there's no way out of that.
    If your "application is a complex one" then you would be better advised to understand threads than to try and pretend that they don't exist. For a start, if you don't think you're using threads then you're destined to run in to all sorts of problems as regards an unresponsive GUI, as you're probably now finding out.

  • How to use threads to reconnect a socket to a server in TCP/IP

    I want to know how to reconnect a socket to a server in TCP.
    Actually i wanted to do reconnection whenever a SocketException for broken connection etc. is thrown in my code. This I want to do for a prespecified number of times for reconnection in case of broken connection.When this number decrements to zero the program will exit printing some error message. I was planning to use threads by way of having some Exception Listeners but i am not sure How?
    Any suggestions will be really helpful..
    please help.
    Edited by: danish.ahmed.lnmiit on Jan 28, 2008 2:44 AM

    I want to know how to reconnect a socket to a server in TCP.There is no reconnect operation in TCP. You have to create a new Socket.

  • How to use Threads in Java?

    Hi all,
    I want to run many programs in the same time. So i want to know if anybody can help me using threads in java. Any help or code will be very appreciated!
    Thanks in advance,
    A. Santos

    All you have to do is create classes that extend Thread, implement their run() methods and then instantiate and call their start() methods:
    public class Class1 extends Thread {
      public void run() {
        // do what you need to do
    public class Class2 extends Thread {
      public void run() {
        // do what you need to do
    public class Class3 extends Thread {
      public void run() {
        // do what you need to do
    public class Main {
      public static void main (String [] args) {
        Class1 c1 = new Class1();
        Class2 c2 = new Class2();
        Class3 c3 = new Class3();
        c1.start();
        c2.start();
        c3.start();
    }

  • How to stop a class which don't use thread is running

    i have a class call my.class, in my application, i use a button "start button" to run this class by call: my.main(new String[0])
    now I want to use another button call "stop button" to stop my.class.
    If in my.class I don't use thread, have any way to stop it
    please help me, it verry importand for me
    Any help will hightly wellcomed

    I take it that TimTheEnchanters reply to this question was scrubbed by your browser?
    http://forum.java.sun.com/thread.jspa?threadID=579074&tstart=30

  • I want to download a game rated 12  but I don't want my children to use it, how can I do this?

    I want to download a game rated 12+  but I don't want my children to use it, how can I do this?
    Is there a way to hide or lock a game to prevent them accessing it?
    thanks in advance

    There is nothing you can do...there are no apps like that unless you jailbreak your iPad.
    Hope this helps you.

  • How to print out multilingual reports from the main report using Xliff temp

    Hi all,
    How to print out multilingual reports from the main report using Xliff temp?
    When I want main report call subtemplate and finish xliff tranlation
    <?for-each@section:INVOICE?><?end for-each?>
    <?import:xdo://XXIH.XXNR_XXINVPRINT_SUB.en.FI/?>
    <?start:body?><?call:Header?><?call:Line?><?call:Weights?><?call:Banks?><?end body?><?call:Footer?>
    Prints out fine with Finnish translation
    But if I want in main program to check what language is used e.g.
    if trx_number = 142 call Finnish translation and if trx_number =144,
    call English translation.
    <?for-each@section:INVOICE?><?end for-each?>
    <?if:TRX_NUMBER=’142’?>
    <?import:xdo://XXIH.XXNR_XXINVPRINT_SUB.en.FI/?>
    <?start:body?><?call:Header?><?call:Line?><?call:Weights?><?call:Banks?><?end body?><?call:Footer?>
    <?end if?>
    <?if: TRX_NUMBER=’144’?>
    <?import:xdo://XXIH.XXNR_XXINVPRINT_SUB.en.US/?>
    <?start:body?><?call:Header?><?call:Line?><?call:Weights?><?call:Banks?><?end body?><?call:Footer?>
    <?end if?>
    Prints out always in English and never the Finnish translation.
    Program goes fine to if branch but does not print out Finnish
    Does anybody know what could be wrong?
    BR
    Kari

    Thanks Amit,
    I have two layout, main-layout and sub-layout
    Main layout call subtemplate
    I have registered layout and xliff-file
    Main template
    Localized Templates
    File Name           Language Territory
    XXNS_INVOICE_MAIN.rtf      English
    SUB template
    Localized Templates
    File Name           Language Territory
    XXNS_INVOICE_SUB.rtf      English
    Translatable Template
    File Name           Language      Territory
    XXNS_INVOICE_SUB.rtf      English      United States
    Available Translations
    Language Territory Progress
    English Finland Complete
    If main report call subtemplate and finish xliff tranlation
    <?import:xdo://XXIH.XXNR_XXINVPRINT_SUB.en.FI/?>
    Prints out fine with Finnish translation
    But if I want in main program to check what language is used e.g.
    if....
    <?import:xdo://XXIH.XXNR_XXINVPRINT_SUB.en.FI/?>
    .....end if;
    if....
    <?import:xdo://XXIH.XXNR_XXINVPRINT_SUB.en.US/?>
    .....end if;
    Prints out always in English and never the Finnish translation.
    Program goes fine to if branch but does not print out Finnish
    Do you it's set up problem or program problem
    BR
    Kari

  • How to create a timer function by only using Threads

    I have used Timer & Timer Task but since they r only available for JDK1.3 and i need this to work on 1.2 also can any one tell me if i can create the same function using Threads.

    i had to do the same (heres roughly what i used...)
    interface TimerTask{
    public void timeout();
    class Timer extends Thread{
    private int delay;
    private TimerTask user;
    Timer(int delay,TimerTask user){
      this.delay=delay;
      this.user=user;
    public void run(){
      try{
       Thread.sleep(delay);            //*
      catch(InteruptedException IE){};
      user.timeout();                  //*
    }as you can see, very rough, but the basics
    refinements could be to add some flags to alter its behaviour..
    like, a loop if you want recuring events
    the commented lines might be rearranged if you dont want it to generate an event just because there is some shut down going on
    as it is an instance of a class could only use 1 Timer, to change this TimerTask.timeout() could be changed to TimerTask.timeout(Timer) so you could determine which Timer had triggered

Maybe you are looking for

  • RMA'ing GPU due to leaking fans

    I have two R9 280X Gaming cards that are suffering from leaking fans and noisy bearings. As far as I know (see quote below from MSI employee) this is a well known issue and the solution seems to be to RMA them to MSI for replacement. However that's p

  • Error when posting Excel Journal file.

    My Journal file checks in correctly, but I receve this error when I post. Unable to copy archive File to ArchiveID: 29740 I have checked the archive table and this line item exists. Also, if I continue with validation and export, everything works cor

  • Seperate GUI & HTML?

    I have results in a form of a Swing JTable. How do I code using design patterns to not update to JTable GUI, but put the results in a HTML table file? That way can have one application that can be a Swing compliant or HTML compliant? Any smart way wi

  • Business Intelligence SDK

    In which forum Business Intelligence SDK Application Development questions should be posted? Can you send me the link, please?

  • Alerts in delegate iCal 6.0 in Mountain Lion not allowing to set default

    I'm using iCal 6.0 with OSX 10.8.2 When syncing iCal with my Google calendars all is well. However, when I add an event in any one of the delegate calendars in switches the default alert from "None" to "9 a.m. the day before" etc. I have logged into