How to call a method once per ms in Java - java

HI.
I want a function in java that automatically called.
for example wen we use Time class like blew
the actionperformerd() function call every 1second.
Timer time = new Time(10,this);
.
.
.
public void actionperformed()
{
timer.run;
//i want move a pic every 1millisecond.
}
my problem is that Timer class only accept int value and it's minimum
value is 1 second and i want call actionperformed every 1 millisecond.

Java Timer accepts milliseconds in parameters. So you can do
new Timer().schedule(new TimerTask() {
public void run() {
// do stuff
}
}, 1, 1);
But to have real-time functionality with milliseconds precision you may need to switch to C.

Try some classes from java.util.concurrent, and ScheduledThreadPoolExecutor can do the thing you want to do:
public static void main(String[] args) throws Exception {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10);
executor.schedule(new Runnable() {
#Override
public void run() {
// Do something here.
}
}, 1, TimeUnit.MILLISECONDS);
}
BTW, the timer class can't run a job periodically accurately, it can only create one thread to run the task.

You could use a separate Thread
class MyThread extends Thread {
public void run() {
while (!interrupted()) {
try {
// move my object, then sleep for a millisecond
sleep(1);
} catch (InterruptedException e) {
}
}
}
}
However, in practice, you will rarely manage to have you move function called every 1 ms because other threads are also consuming processor time. So you need to take into account the actual time between the end of the previous thread loop and the current time.
I suggest you read lots of tutorials about "Game Loops", you'll learn how to organise the functions moving objects, rendering, ...
This one is an interesting article. Made for Android but can be applied to standard Java.

If this happens to be something graphical be aware that you actually update the screen in the EDT (event dispatch thread). The GUI is not multithreaded.
By hammering your EDT with updates in 1 ms intervals (even worse if you do this per pic) you might in effect make the GUI unusable - it is busy redrawing is stead of responding to user input.
I really don't know whether that effect occurs 1 ms intervals, but the single threaded design of the GUI is something to take into account.

Related

Javafx - How can I delay the display of a new line in my textarea?

So I got this new game I am coding.
Long story short, there is a textarea in my GUI which acts as an event displayer. When you fight a monster, this textarea is used to display lines of text such as "You deal 3 damages to skeleton" or "Skeleton casts fireball on you and hit you for 5 damages".
The code works in a way so that the monster attacks after you. So as soon as you hit the "Attack" button, both the line saying what you did and the line saying what the monster did appears at the same time in the textarea. Like if the monster could hit you at the speed of light right after you hit it.
What I want to do is to delay the display of the monster's line. So that when I hit the "Attack" button, the textarea displays the line of what I did, then wait a second and then displays the monster's line.
I tried using the Thread.sleep() method, but all it does is pausing the UI for 1 second and then both lines appear in the textarea.
private void attackBareFists() {
if (initPJ > enemyINIT) { // Player has more initiative ->
// Player attacks first
turnPlayerBareFists(); // This method will display the player's line
if (!endTurn()) { // endTurn() checks that the player or the monster
// are still alive before continuing the fight
delay();
turnMonster(); // This method will display the monster's line
endTurn();
}
} ... // The code continues, but it's the same as above except monster attacks first
}
/**
* Wait for some time
*/
private void delay(){
}
What should I put in delay()? This is where I've tried Thread.sleep(1000). And like I said, doing so caused the code of turnPlayerBareFists() and turnMonster() to be executed after delay(). Any help would be appreciated.
I think a better/more consistent way to achieve this is by using timers. You could use any java implementation, though javafx itself provides several mechanism for timed events.
One way is the TimeLine
Timeline timeline = new Timeline(new KeyFrame(
Duration.millis(1000),
ae -> doSkellyTurn()),
new KeyFrame(
Duration.millis(1000 + 1000), // as mentioned by fabien, the time offset is relative to the 'start()' method, not to its previous keyframe!
ae -> endSkellyTurn()));
timeline.play();
The above way is also the basics for javafx animations (as you can read in the documentation)
This blog shows some more examples of how you can accomplish timed tasks. (Ps. It uses reactFX as well!)
Great question! I suggest using something like this:
public static void delay(long delayMs, Runnable toRun){
Thread t = new Thread(() ->{
try { Thread.sleep(delayMs); }catch(InterruptedException ignored){}
Platform.runLater(toRun);
});
t.setDaemon(true);
t.start();
}
This way, you can specify exactly how long the delay should between the call to delay() and when your code should be executed. Essentially you pass a Runnable containing whatever code you want to run as the second argument of the method.
For example, this would mean that your the monster's turn would be represented as such:
if(!endTurn())
delay(1000, ()->{ turnMonster(); endTurn(); });
If, for some reason, you don't want to use lambdas (the "()->" things), you can use this:
public static void delay(long delayMs, Runnable toRun){
Thread t = new Thread(new Runnable(){
public void run(){
try { Thread.sleep(delayMs); }catch(InterruptedException ignored){}
Platform.runLater(toRun);
}
});
t.setDaemon(true);
t.start();
}
And your monster code would look like this:
if(!endTurn())
delay(1000, new Runnable(){ public void run(){ turnMonster(); endTurn(); } });
If you're wondering, Platform refers to javafx.application.Platform and the runLater() method will always post the given Runnable to the JavaFX thread, so it's safe to pass it code that manipulates the UI.

Introduce delay between calling a set of methods in java

I have a specific use case where I have 10 methods I need test by calling them continuously for about 5 minutes. To avoid the loading the backend handling these calls, I plan on having a one second delay between each method call.
My code looks like something like this:
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) // start i at 1 for initial delay
{
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run()
{
callMethodA();
Thread.sleep(1000);
callMethodB();
Thread.sleep(1000);
callMethodC();
Thread.sleep(1000);
callMethodD();
Thread.sleep(1000);
callMethodE();
Thread.sleep(1000);
callMethodF();
}
}, 30000 * i); // 5 second intervals
}
}
I wanted to know if there's a better way to introduce the delay rather than using Thread.sleep() after every method call. I wasn't sure if the ScheduledExecutorService can be used for this purpose?
I have a specific use case where I have 10 methods I need test by calling them continuously for about 5 minutes. To avoid the loading the backend handling these calls, I plan on having a one second delay between each method call.
For this purpose, I don't see the need for scheduling. You can simply loop n times and call the methods with some sleep in between:
Runnable[] calls = {
() -> callMethodA(),
() -> callMethodB(),
// ...
};
for (int i = 0; i < 5; i++) {
for (Runnable runnable : calls) {
runnable.run();
Thread.sleep(1000);
}
}
Depends on the precision you are looking for.
For all practical purposes, sleep is fine. It's quite literally putting the thread to sleep for some amount of time and the process is doing other stuff in the meantime.
A more robust approach to task scheduling in general is a ScheduledExecutorService, so you might want to consider that instead.
However, what is not very nice about your code is that you are basically enumerating the method calls. Consider using multiple schedulers with some offset (i.e. start them at different times such that the tasks do not overlap such that you don't need to sleep inside the task).

Java do something in X minutes

I'm looking for a way to do something every X minutes.
For example in a game you will be playing then every 3 minutes activate
foo();
but I'm not sure how to do this given that other actions will be going on. Ie, we cannot just wait 3 minutes then do foo() instead the rest of the program must be running and the user can invoke other methods but in the background we have to be counting and getting ready to do foo() when the time is ready.
If anyone can give me a starting point I'd much appreciate it!
You want some manner of separate thread that has a timer in it. A built in structure is the ScheduledExecutorService.
A tutorial on how to use one can be found here
The tutorial is kind of confusing and ugly, so here it is summarized in three steps:
1) Define a thread executor (something that manages your threads)
int x = 1; // However many threads you want
ScheduledExecutorService someScheduler = Executors.newScheduledThreadPool(x);
2) Create a Runnable class, which contains whatever it is you want to do on a schedule.
public class RunnableClass implements Runnable {
public void run() {
// Do some logic here
}
}
3) Use the executor to run the Runnable class on whatever level of your program you want
Runnable someTask = new RunnableClass(); // From step 2 above
long timeDelay = 3; // You can specify 3 what
someScheduler.schedule(someTask , timeDelay, TimeUnit.MINUTES);
Use a Timer in a separate Thread!
https://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
Bryan Davis pointed the solution, but the link provided is not very elegant. here is a short sample:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
// 3 = number of thread in the thread pool
scheduler.scheduleAtFixedRate(new Runnable()
{
public void run()
{
// do something here
}
}, 20, TimeUnit.SECONDS);
For a single threaded game, you can just check every loop whether it is time to do foo(). For example:
long lastTime;
long timeBetweenFoosInMillis = 3*60*1000; //3 minutes
public void loop(){
while(true){
doOtherGameStuff();
if(isFooTime()){
foo();
lastTime = System.currentTimeMillis();
}
}
}
private boolean isFooTime(){
return System.currentTimeMillis() >= lastTime + timeBetweenFoosInMillis;
}
You probably want to use Threads. You can put your foo() function in one and make it sleep and execute every X minutes, and put the rest of the program in other threads so your other functions can keep executing. Here is a good tutorial on how to set up a multi-thread program in java: http://www.oracle.com/technetwork/articles/java/fork-join-422606.html

Correct use of wait()/notify() for a Tetris game

I’m writing a Tetris-like game for Android and I’m trying to implement the “real-time part”. I have something which seems to work, but I want to be sure that my implementation is correct.
What I want is:
The shapes are going down at a fixed rate (say that I want to wait n milliseconds each time the y of the shape is decremented)
The player can drop the shape at any time and the timer waiting for the n milliseconds must then be immediately interrupted and start again only for the next shape
When the shape is droped or when the shape cannot go down anymore, the game waits m milliseconds before creating another shape
The system have to be able to stop the thread at any time
What I am doing is the following (the system can stop the thread with interrupt()):
class TetrisThread extends Thread {
private int n = 3000; // for testing purposes, in the real game n will be smaller ;)
private int m = 1000;
#Override
public void run() {
doDraw();
while(!interrupted())
{
try {
synchronized (this) {
wait(n);
}
doPhysics();
doDraw();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
// This method is the one which will drop the shape, it is called from another thread
synchronized public boolean onTouch([…]) {
[…]
// The shape has to be dropped
dropShape();
notify();
[…]
}
private void doPhysics() throws InterruptedException {
[…]
// The shape cannot go down or has been dropped
sleep(m);
createNewShape();
[…]
}
}
In particular, the part synchronized(this) { wait(n); } looks funny because if I understand correctly this will take a lock on this and release it immediately.
But wait() requires to be used in a synchronized(this) block (why?) and I cannot either synchronize the whole run() method, because then if I try to drop three times the shape during the sleep(m) call, then the three next shapes will be automatically dropped (which is not what I want).
Does this seem correct to you?
Do you have any correction, advice, or remark?
Thank you :-)
The wait() method is used to make the current running thread to wait the object invoking wait() invoke notify() (in this case this). The synchronized(this) part needed to make sure only one thread at that time accessing this.
You can't synchronize the whole run() method, because the run() is from the parent (Thread) class and the parent didn't use synchonized in the declaration.
I don't know how to solve your other problem because I don't get how your program works right now.

Have threads run indefinitely in a java application

I am trying to program a game in which I have a Table class and each person sitting at the table is a separate thread. The game involves the people passing tokens around and then stopping when the party chime sounds.
how do i program the run() method so that once I start the person threads, they do not die and are alive until the end of the game
One solution that I tried was having a while (true) {} loop in the run() method but that increases my CPU utilization to around 60-70 percent. Is there a better method?
While yes, you need a loop (while is only one way, but it is simplest) you also need to put something inside the loop that waits for things to happen and responds to them. You're aiming to have something like this pseudocode:
loop {
event = WaitForEvent();
RespondToEvent(event);
} until done;
OK, that's the view from 40,000 feet (where everything looks like ants!) but it's still the core of what you want. Oh, and you also need something to fire off the first event that starts the game, obviously.
So, the key then becomes the definition of WaitForEvent(). The classic there is to use a queue to hold the events, and to make blocking reads from the queue so that things wait until something else puts an event in the queue. This is really a Concurrency-101 data-structure, but an ArrayBlockingQueue is already defined correctly and so is what I'd use in my first implementation. You'll probably want to hide its use inside a subclass of Thread, perhaps like this:
public abstract class EventHandlingThread<Event> extends Thread {
private ArrayBlockingQueue<Event> queue = new ArrayBlockingQueue<Event>();
private boolean done;
protected abstract void respondToEvent(Event event);
public final void postEvent(Event event) throws InterruptedException {
queue.put(event);
}
protected final void done() {
done = true;
}
public final void run() {
try {
while (!done) {
respondToEvent(queue.take());
}
} catch (InterruptedException e) {
// Maybe log this, maybe not...
} catch (RuntimeException e) {
// Probably should log this!
}
}
}
Subclass that for each of your tasks and you should be able to get going nicely. The postEvent() method is called by other threads to send messages in, and you call done() on yourself when you've decided enough is enough. You should also make sure that you've always got some event that can be sent in which terminates things so that you can quit the game…
I would look into Locks and Conditions. This way you can write code that waits for a certain condition to happen. This won't take a lot of CPU power and is even much more efficient and better performing than sleeping .
To make a thread run for an infinite time:
final Object obj = new Object();
try {
Thread th = new Thread(new Runnable() {
public void run() {
synchronized(obj) {
try {
System.out.println("Waiting");
obj.wait();
System.out.println("Done waiting");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
});
th.start();
System.out.println("Waiting to join.");
// Dont notify; but wait for joining. This will ensure that main thread is running always.
th.join();
System.out.println("End of the Program");
} catch(Exception ex) {
ex.printStackTrace();
}
You may add Thread.sleep() with appropriate time to minimize useless loop iterations.
Another solution is using synchronization. While threads are not required to do anything, they enter into a sleeping state on a monitor using the wait() method, and then when the turn comes, required thread is woken up by the notify() method.
Actor model seems suitable for this scenario. Each person sitting on the table and the table itself can be modelled as actors and the event of passing the tokens and starting and stopping of the game can be modelled as messages to be passed between the actors.
As a bonus, by modelling the scenario as actors you get rid of explicit manipulation of threads, synchronization and locking.
On JVM I will prefer using Scala for modelling actors. For Java you can use libraries like Kilim. See this post for a comparison of Actor model related libraries in Java.
One Way is to use while loop but keep a check i.e
while(true){
if(condition!=true){
Thread.sleep(time);
}else{
break;
}
}
This way if your condition says game is not over it will keep person thread at sleep and memory consumption will be very low.
You should test for a condition in the while loop:
while (!gameOver)
{
do_intersting_stuff();
}
Heavy CPU load is typical for busy wait. Is your loop actually just checking a flag over and over, like
while (!gameOver)
{
if (actionNeeded)
{
do_something();
}
}
you might change to another notification system to sleep and wake up, as this just burns CPU time for nothing.

Categories