How can I start every instance of a certain class on a brand new thread?

Viewed 2118

I'm writing a game for fun where players have sprites that can jump around and shoot lasers. It can have up to three players. My class Sprite is the same for all three players, just has a different control layout for each depending on the player # it is given in its construction. Sprite uses a KeyListener to function.

In order for me to have multiple players doing things simultaneously (like shooting lasers or jumping) I need to have each Sprite object that is created in a separate thread. I know I can use implements Runnable on the Sprite class, however this only runs the code in the run() method on the new thread. This doesn't work because Sprite has keyPressed() and other such things in it that won't be on the new thread.

The one thought I had was to use a "helper" class and have that implements Runnable then in its run() method create the new Sprite object. This seems like a kind of messy approach however. Is there any way for me to create all new Sprite objects on a brand new thread (KeyListeners and all included on this thread)?

Code:

public class Sprite() implements KeyListener { //I want this class on a brand new thread
    int x;
    int y;
    int width;
    int height;
    Image spriteImage; 

    //code/methods for stuff

    //key listeners:

    @Override
    public void keyPressed(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

}

Current Solution:

public class SpriteStarter(/* Sprite class parameters go here */) implements Runnable{

    void run() {
        Sprite s = new Sprite(/*params*/);
    }

}

...

class Linker() {
    public static void main(String args[]) {
        SpriteStarter s1 = new SpriteStarter();
        SpriteStarter s2 = new SpriteStarter();
        Thread t1 = new Thread(s1);
        Thread t2 = new THread(s2);
        t1.start();
        t2.start();
    }
}

Edit:

Okay, after A LOT of great feedback, its become obvious to me that my game should be a single-threaded thing. I apologize for not realizing that, I haven't done much game programming so this was a new thing for me. My new thought is to have an ArrayList that on keyPressed() fires adds the pressed keys to the list. Than in the Sprite classes I'll have an update() method which looks at the pressed keys and updates coordinates accordingly. Update() will then be called at a fixed interval through a java.awt.Timer. This seems like it may work to me but I'm not sure so let me know! Thanks again to everyone. Also, I'd still appreciate an answer to the original question (being: how to start every instance of a class on a new thread) since it could be helpful for future programs.

1 Answers
Related