I was wondering how I would use multiple threads in an applet at the same time. I'm creating a game like Space Invaders and I wrote all the code for the enemies to move and shoot but I can't add the player in to move around using the keyboard at the same time as the enemies. So I was thinking I needed to have 2 different threads running. I would upload the code but there is a lot of different classes and code.
If someone could help me out quick I would appreciate it a lot.
Yes they are independant of each other i got my single thread that moves the enemies in the run() method that i overloaded and all my movements are in the paint method.
should they be somewhere else?
You can do this with one thread, or with two.
Either way you have to work with the GUI Event Thread to do all the screen updates.
There is a lot of reference on the web discussing how to do this. If you google java space invaders you get 1.5 million hits and usually the first page of such a search has more than what you need.
I think the enemies are independent and have particular movements, if that's the case, you will need several threads enemy, and for each player, but taking into account the resources of the computer you should deal with a manager thread or task managers.
These are links that maybe help you.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html
Related
Let's imagine a simple Java program, where there are 5 2D marbles moving around in a circle in a fixed order. You can control the speed of every marble keeping in mind that slower marble is blocking the marble moving faster (they can't overtake). They all move in one direction in a circle. What would be the best way to program this? The idea is to assign a separate thread to every marble, that's actually one of the requirements.
Then I create five threads, synchronize the "move" method on some object common to all threads. The next step is checking whether I can move the marble forward, if there is some free space. So before I move, I check if there is free space and then take action. Is it necessary or at least a good idea to use wait() and notify() mechanism here?
Thanks for help.
Well, I'm not going to code your homework for you, but here is a high level look at it.
You will need each marble to update it's position at regular intervals, so some type of looping is required. This loop is commonly known as a game loop. Here is a discussion of various types of them, going from simple to complex. http://www.java-gaming.org/index.php?topic=24220.0 For your project, something simply may be sufficient, but I don't know the requirements of it.
Each time a marble tries to move, it must check to make sure it isn't being blocked. If you have the move method synchronized, as you mentioned, then only one marble should be able to move at a time, so that should avoid concurrency issues.
Except for using a Thread.sleep in your game loops, I don't see any reason for you to doing any waiting. Java has a synchronize keyword, which can be used to lock the shared object that you mentioned using for movement, to avoid the concurrency issues. So I don't believe wait and notify are necessary.
Just my thoughts, I hope it is of some help.
I am implementing a game and I want to ask the player to click on a specific view.
I want my control thread to wait until I get a value back (I have clicked on the view and handled the result). Currently I am doing this by creating a thread, running a method that asks them to click and then entering a while loop that is terminated when the mouse click event changes a variable used in the while loop.
I am writing a game where I have a thread constantly receiving events. On a specific event, I want to prompt the user for a response, but to do this would require me to be on the JavaFX thread (to my knowledge).
Is there a better way of doing this in JavaFX? Thanks!
There are several tools "hidden" in the JDK documentation on threads that can help you resolve this type of issue. Usually when we make a routine code wait for some condition that can proceed we use threads synchronizers.
I want my control thread to wait until I get a value back [...]
CountDownLatch, CyclicBarrier and FutureTask may be classes that can solve your problem. The functionality of these is quite simple. They have the function of stopping threads and release them when some condition is met. The difference in each of these classes is just semantics applied for termination and release threads. Read the documentation of each and see which one is most comfortable to you.
You can also take a look at other sources of study. There is no better source of study in the world (in my opinion) than the content within the book "Java Concurrency In Practice" by Brian Goetz. I assure you that you will become able to easily manipulate threads if you buy this book (or at least gain an incredible knowledge on the subject). Make it clear that you do not need to buy the book to solve your current problem. Buying the book is just my suggestion for you to have more knowledge about threads. You probably will solve your problem by looking at the documentation of classes that synchronize threads I mentioned.
Good luck in your projects. ;)
I have a Swing program that executes 2D animations using Swing Timers. With each button click there are several timers created to animate several different components - some of them moving off the screen and others moving on. (I do not know ahead of time what animations will need to be executed with each button click, but it isnt a problem to distinguish between the two "types" of animations at runtime - they're initiated from different methods, and thus its easy to imagine adding them to two different "queues" - a queue of outgoing items and a queue of incoming items. Having done so, I could then implement the basic strategy of calling a
That said - that all only makes sense to me intuitively, heuristically - I haven't figured out how to implement it in practice. What would those "queues" actually be, and what class would hold and later execute them?? Presumably one that implements Runnable, creating a second thread that can execute the animations with tighter control on how they proceed? Or does the event-dispatch thread give me the ample control here: Is there a way to use SwingUtilities.invokeAndWait() (or something like it) to collect all the animations to be performed, while assigning priority to those of a certain class, or that are marked in a certain way?
I would suggest taking a look at the design of some of the existing animation engines like:
The Timing Framework
Trident
The Universal Tween Engine and AurelienRibon / sliding-layout which uses the Tween Engine.
Generally what these engines tend to do is have a central "clock" which ticks at a regular interval. They then provide callback functionality to notify interested parties that a "tick" has occured.
They then offer a series of layers on top of this concept to make it easier to interact with, such as providing a time range for animations, presented as a percentage over time (rather than a physical time measurement), which can be used to calculate fractions of change.
The also provide interpolation, allowing you to affect the speed of the animation through the time cycle (such as slow in, fast out effects).
This approach reduces the overhead of having to have multiple Timers running, which may reduce the performance over time while, providing a separation model, so each "animation" is it's own entity.
Personally, I'd evaluate each one and see which best meets your needs and run with, but if you really want to do it yourself, they provide a good starting point for ideas and designs
To give some background information, I'm currently working on a Java coded pinball game. I'm keeping it in an MVC design model. It has a fairly realistic physics system that allows it to work collisions, gravity, friction etc. The system runs on a 20 FPS system right now.
The problem I'm having is that the physics loop that checks for collisions in the system works by running a method that using the current velocity of the ball calculates the time until the next collision. The most effective way for this to work would obviously be to keep running the check to account for the movement of the ball between checks to get it as accurate as possible, and if the time until collision is less than the time until the next check, then carry out the collision.
However, right now the system I am working with can only run the loop 20 times per second, which does not provide as accurate results as I would like, particularly during times of high acceleration, such as at ball launch.
The timer loop that I use is in the controller section of the MVC, and places a call to the physics section, located within the model. I can pass in the time remaining at the time the method is called in the controller, which the physics system can use, however I don't know how to run the loop multiple times while still tracking the remaining time before the next screen refresh?
Ideally I would like to run this at least 10 times per screen refresh. If anybody needs any more information please just ask.
Thanks for any help.
So the actual problem is that you do not know when the the collision will happen and when the next frame update is?
Shouldnt these be seperate running tasks? One thread that manages the collision detection and one that does the updating? each thread can run on its own interval (Timer.addTask(...)) and they should propebly be synchronized so colission/location updates are not performed when the render thread is executed.
Hope this answers your question.
Regards, Rob.
I'm writing a game in which players write AI agents that compete against one another, on the JVM. Right now the architecture looks like this:
A core server module that handles the physics simulations, and takes messages from the players as input to alter the world. The core also determines what the world looks like from the perspective of each of the players, based on various rules (think fog of war).
Player modules receive updated versions of the world from the core, process them, and stream messages to the core as inputs based on that processing.
The idea is that the core is compiled along with two player modules, and then the simulation is run producing an output stream that can be played back to generate visualization of the match.
My question is, if each of the players runs on a single Java thread, is it possible to ensure that the two player threads get equal amounts of resources (CPU time, primarily, I think)? Because I don't control the nature of the processing that each AI is doing, it's possible that one of the players might be extremely inefficient but written in such a way that its thread consumes so many resources the other player's AI is resource starved and can't compete fairly.
I get the feeling that this isn't possible without a hard realtime OS, which the JVM isn't even close to being, but if there's even a way to get reasonably close I'd love to explore it.
"Player modules receive updated versions of the world from the core, process them, and stream messages to the
core as inputs based on that processing". This means that player module has a loop inside it which receives update message and sends result messages to the core. Then I would use lightweight actor model, each player being an actor, and all actors use the same ExecutorService. Since activated actors go through the same executor task queue, they got roughly the same access to CPU.
Your intuition is right that this isn't really possible in Java. Even if you had a real-time OS, someone could still write a very resource intensive AI thread.
There are a couple of approaches you could take to at least help here. First be sure to give the two player module threads the same priority. If you are running on a machine that has more than 2 processors, and you set each of the player module threads to have the highest priority, then theoretically they should both run whenever they have something to do. But if there's nothing to stop the player modules from spawning new threads themselves, then you can't guarantee a player won't do that.
So short answer is no, you can't make these guarantees in java.
Depending on how your simulation works, maybe you can have a concept of "turns". So the simulation instructs player 1 to make a move, then player 2 makes its move, and back and forth ,so they can each only make one "move" at a time. Not sure if this will work in your situation though.
If you have any knobs to turn regarding how much work the threads have to do (or just set their priority), you can set up another thread that periodically monitors threads using ThreadMXBeans and find their CPU usage using ThreadInfo.getThreadCpuTime. You can then compare each players CPU time and react accordingly.
Not sure if this is timely and accurate enough for you, but over time you could balance the CPU usage.
However, splitting the work in packets and using Executors like suggested before should be the better way and more java-like.