Java short delay - java

I have been trying to create a way to recreate the pokemon's "Rolling text" where one letter appears at a time. The problem is being able to create a timer short enough to make it reasonable.
This is what i have tried:
public static void roll(String text) {
int i = 0;
while(i < text.length()) {
try {
Thread.sleep(200); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
System.out.print(text.charAt(i));
i++;
}
}
This will work fine if i set the value in Thread.sleep to anything above 250. The problem is, if i set seconds below 250 then it will wait the entire length of time (If i tell it to wait 100 millisends 100 times, it will wait 10 seconds) before outputting anything.
Im not sure if this is a problem with the type of timer itself or if there is something else at play here.

You can use System.out.flush(); to force the buffer to be written out.

Related

java- How do I create a String check with a delay of a certain amount of time?

I am learning java and so far I have created a password check using if statements. However I inserted my working String check into a while loop and added Thread.sleep(3000); for a 3 second delay, however once I completed that my GUI just keeps lagging and freezing on one page as if the button was pressed. Can somebody please show me how to make a working example of a code with a String check and after a certain amount of tries a delay to stop the user from trying again?
(here is what I have:)
//var declaration
boolean match = false;
String1 = "hi";
String2 = (I know this is not code but just to omit some code:) userInput
int time = 3000;
int attempt = 0;
//check
while(!match && attempt < (maximumTries+1)){
if(String1.equals(String2)){
System.out.print("match");
}
else if(attempt < 11){
attempt++;
System.out.println("Failed:" + attempt);
}
else{
attempt++;
System.out.println("Please try again later you have:" + attempt + "failed attempts");
try{
Thread.sleep(time);
}
catch(InterruptedException ex) {
Logger.getLogger(PasswordEntry.class.getName()).log(Level.SEVERE, null, ex);
}
time = time + 1000;//1 second more every time
}
}
your code is doing an infinite loop once the first attempt does not match.
in each of the iterations of your loop there is no change at all, aside from incrementing the counter. so the counter just increases forever (with some delays in between).
it seems the reasoning behind your code was that String2 got updated with user input inside the loop not outside. This way, on each iteration you would have a different String2 to compare against.
That's your issue, not the way you delay between attempts (that for sure can be improved in any case).
You should avoid using the Thread.sleep option since it completely freezes the main thread. You could also try creating another thread, which will be frozen and later in gives a callback to the main one. For example through a boolean variable. I'd also agree on the timer solution mentioned by BladeMight.

Producer/Consumer Threads Concurency Java

I have a producer that produces products and a consumer that consumes them. What I want is, if a product is not consumed in 5 minutes I want it to be destroyed.
This is the part of the producer:
boolean full = false;
public void produce(int p) throws RemoteException {
//choses a or b randomly
//if a or b spot is occupied, thread must wait()
synchronized(this){
if ((int)((Math.random()*10)%2) == 1){
while (a!=-1){try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
a = p;
if (b!=-1) full = true;
notifyAll();
}
else {
while (b!=-1){try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
b = p;
if (a!=-1) full = true;
notifyAll();
}
}
}
a & b are supposed to be my products.
I really don't know how can I measure that time for example when the thread is waiting or a client isn't trying to consume that product. This piece of code , is running on a RMI java server.
I'd just using a scheme like this: when you produce something use java.util.Timer() to set a timer for 5 minutes in the future. When the item is consumed, .cancel() the timer. If the timer goes off, do whatever cleanup you need to do.
It looks like you are implementing a queue with 2 slots, the 2 slots being a and b. But the strategy of chosing a random slot isn't optimal. You might wait for a slot while the other is empty. Also, the consumer cannot tell which one of a or b you produced first.
Anyway, if I understand the code well, you could
save the current time at the time you enter the loop.
every time you wake up from wait(), compute the delay since the entry. If it exceeds your time limit, return or throw an exception. Else, check if the slot is available.
to make sure not to wait forever, you should specify a delay on your wait. You could either wait a fixed time, maybe 1 second, or compute the wait time remaining until the 5-minute deadline.

How do I check how many events are happening within 2 seconds? (timer)

I need to check how many events are detected within 2 seconds. I have the timer working and I have everything else working...but I ran into a problem: the loop only checks one time, per second and I can't seem to figure out how to fix that. I need it to check constantly during these two seconds to see how many events there were in total!
Here is what I have:
int seconds = 0;
System.out.println("Seconds: " + seconds);
while(seconds < 2)
{
//Wait 1 second
try {
Thread.sleep(1000);
}
catch(Exception e) {}
seconds++;
System.out.println("Seconds: " + seconds);
//This needs to be looping the whole time.
//But right now, it's being blocked and only checked once
if(eventDetected() && seconds <= 2){
events++;
}
}
So you can see my problem. I can't split them up because then the second timer would run, and THEN eventDetected() would be checked. I need it to check constantly DURING the two second timer...so I basically need both things to happen at once. Is there any way I can do this?
Thanks for any help ahead of time!
I think your design pattern needs work -- I don't know what type event you're looking to detect, but no matter how short your sleep time is, there's a chance you could miss an event using the current pattern. Here's what I suggest:
Have eventDetected() increment your events counter. That way, you won't miss an event.
Then, you just need a way to turn on and off listening (and perhaps resetting the event counter). If you're sure that in you're current pattern you are really in a different thread that won't block your eventDetected() method, you could set a flag to check. For example:
When you want to start listening:
listenForEvents = true;
In eventDetected():
if (listenForEvents) { events++; }
When you want to stop listening (for example, after your Thread.sleep() call):
listenForEvents = false;
With multithreading, make sure to watch out for concurrency issues checking and setting the variables, of course.
I would tell you what kind of event I have to keep track of but then I'd have to kill you :D
Answered my own question. Hopefully this will help anyone else out who has a similar problem at some point! I looked up multithreading a bit...
I created a new class EventTimer which implements Runnable, with a public field for seconds:
public class EventTimer implements Runnable{
int seconds;
static int timerThreadCount = 0;
Thread t;
public EventTimer() {
timerThreadCount++;
this.seconds = 0;
t = new Thread(this, "Event Timer");
t.start(); // Start the thread
}
#Override
public void run() {
// TODO Auto-generated method stub
while(seconds < 2)
{
//Wait 1 second
try {
Thread.sleep(1000);
}
catch(Exception e) {
System.out.println("Waiting interupted.");
}
seconds++;
System.out.println("Seconds: " + seconds);
}
}
}
Then I used an instance of the EventTimer, and used a while loop & if statement to solve my problem.
EventTimer t = new EventTimer();
while(t.seconds < 2){
if(eventDetected()) events++;
}
It was actually quite simple! I realize that each iteration of my loop of operation (since the entire code piece above is inside an infinite loop) will create a new EventTimer thread and I will eventually run into memory problems however. How would I close/end a thread after the timer has reached 2 seconds?

Game Timer Damage Delay

Me and a friend of mine are working on a game and basically, we have a hitbox set up where if our character hits it (a spider), the character loses health.
Because we are using a for loop, the inevitable happens, the player loses their health 1 by 1, but so fast the human eye can not see it. Therefore we need a timer, pause, or something for every x amount of time the player is hitting the spider. Here is our code:
if (ResetEntities.spiderObj.intersects(ResetEntities.blueCharacterObj)) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < 100; i++) {
if (ResetEntities.blueHealth < 0) {
ResetEntities.blueHealth = 0;
Frame.blueHealthLabel.setText("Health: "
+ ResetEntities.blueHealth);
} else {
ResetEntities.getBlueHealth(ResetEntities.blueHealth - 1);
Frame.blueHealthLabel.setText("Health: "
+ ResetEntities.blueHealth);
}
}
}
In this code we have an if statement to check for intersection. I tried to sleep the script, (I realized 10 is incredibly fast, but 1000 lags horribly, so Thread#sleep isn't the way to go I imagine). Then we have a for statement to run 100 times (being the players health). Then we have an if seeing if the health goes below 0, set back to 0, so the player can't get negative health. If it's not below 0, we do the else and subtract 1 health. But as I said this runs too fast to see.
Any help?
The traditional way - and in my opinion best way - to do it is, to make the wounded character invulnerable until a specific point in time: When the character gets wounded, check the game-timeline (or if you dont have one then the current millis-count) then add a specific time eg 1 second (or the character-dependent recovery-time) and remember that timestamp in the character-object. A gametick that wants to wound a character first checks whether the character is still in hidden invulnerability. This is especially good because typically one doesn't really want multiple threads updating the game-state.
Use Timer for your background process' timing. And use javax.swing.SwingUtilities.invokeLater(Runnable) to update your GUI.
The question is unclear, but are you asking how you can stop the health from going down so quick? If so,this is what I would do:
You should have a int value invincibilityTime and set that to 100 once the player is hit, and then every time your game goes through the gameloop it decreases it by one. Put if(invincibilityTime <= 0) before the (ResetEntities.spiderObj.intersects(ResetEntities.blueCharacterObj)) to check if the invicibility period has expired.

Java Delay/Wait

How do I delay a while loop to 1 second intervals without slowing down the entire code / computer it's running on to the one second delay (just the one little loop).
Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
It seems your loop runs on Main thread and if you do sleep on that thread it will pause the app (since there is only one thread which has been paused), to overcome this you can put this code in new Thread that runs parallely
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
//do stuff
}
My simple ways to delay a loop.
I already put the codes here after failing to follow the stackoverflow's standards.
//1st way: Thread.sleep : Less efficient compared to 2nd
try {
while (true) {//Or any Loops
//Do Something
Thread.sleep(sleeptime);//Sample: Thread.sleep(1000); 1 second sleep
}
} catch (InterruptedException ex) {
//SomeFishCatching
}
//================================== Thread.sleep
//2nd way: Object lock waiting = Most efficient due to Object level Sync.
Object obj = new Object();
try {
synchronized (obj) {
while (true) {//Or any Loops
//Do Something
obj.wait(sleeptime);//Sample obj.wait(1000); 1 second sleep
}
}
} catch (InterruptedException ex) {
//SomeFishCatching
}
//=============================== Object lock waiting
//3rd way: Loop waiting = less efficient but most accurate than the two.
long expectedtime = System.currentTimeMillis();
while (true) {//Or any Loops
while(System.currentTimeMillis() < expectedtime){
//Empty Loop
}
expectedtime += sleeptime;//Sample expectedtime += 1000; 1 second sleep
//Do Something
}
//===================================== Loop waiting
As Jigar has indicated you can use another Thread to do work which can operate, sleep etc independently of other Threads. The java.util.Timer class might help you as well since it can perform periodic tasks for you without you having to get into multithreaded programming.

Categories

Resources