How do I make my system wait 5 seconds before continuing? - java

I'm currently working on a Black Jack game in a school project. When the machine rolls, I want to make it wait 5 seconds each time it rolls to make it more exciting. How do I do this?

Use Thread#sleep():
Thread.sleep(5000);
The method can throw InterruptedException if any thread has interrupted the current thread. Usually you would catch the exception and handle it but if your program is single threaded, you don't need to worry about it. So you can just specify that the method calling Thread.sleep throws an InterruptedException:
public void foo() throws InterruptedException {
...
Thread.sleep();
...
}

You can use threading to sleep 5 seconds your current thread
try {
Thread.sleep(5000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
I Think this will help you :)

It can be done using the Thread Class with method sleep
Java Docs Says :
sleep(long millis);
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
Example:-
Thread.sleep(5000);

I guess you should you use a very large loop repetition in any programming language to create a delay.

Related

Thread.sleep() / robot.delay() more accurate?

I want to write a bot for a online game using the Robot class. My problem is now, that the method Thread.sleep() or robot.delay() is to inaccurate. Outside the game they work perfectly fine, with a deviation of approximately only 2 - 3 ms. But when the game is in focus, the methods have a deviation of +5 - +20 ms or even more. That is sadly enaugh to make my bot unusable. Is there any way to make these methods more accurate? Or are there any other ways to solve this problem?
There is no difference
If you browse the source for the JDK, Robot.delay() ends up calling Thread.sleep().
public void delay(int ms) {
checkDelayArgument(ms);
Thread thread = Thread.currentThread();
if (!thread.isInterrupted()) {
try {
Thread.sleep(ms);
} catch (final InterruptedException ignored) {
thread.interrupt(); // Preserve interrupt status
}
}
}
You might be able to give the Java process a higher priority then the game, tasks might be executed more quickly after being given to the scheduler.

How to wait until timer is stopped in java?

I have a method, which is calling a swing timer to start, and after calling this method, i have to wait until the executed timer stops. I tried
while(timer.isRunning(){}
but it didnt worked, it just froze my program. Please help me and forgive me for my bad english.
What you are doing right now is very bad practice as you force your program to run a loop without any meaning. Imagine the timer will never return, in that case you created an endless loop.
Try thread.sleep(). Start the timer before sleep(). The timer will throw a InterruptedException if it has finished. Even better: if you wake up naturally, then you should decide if you want to sleep again and keep waiting for the timer or if you want to throw an error / do something else.
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
As the solution, I used an integer to keep track of the iteration count of my method. When the integer got bigger than a certain number, I knew the time has passed.

Heartbeat in Java: timerTask or thread.sleep()?

I want to implement a very simple client to server heartbeat in java. The most simple approach seems to be through sleep. Consider the metacode below.
class MyClass
Thread heartbeatThread = new Thread();
public void() startHeartBeat{
Thread.sleep(4000);
sock.write("H");
}
Is this an adequate solution, or are there pitfalls I'm not considering?
I've also considered using the java.util.Timer.scheduleAtFixedRate approach. Would this be more robust/reliable? If so, why? Here's an example (it's not as clean IMO):
class HeartBeat
{
Timer timer=new Timer();
public void scheduleHeartBeat(int delay, int period) {
timer.scheduleAtFixedRate( new HeartBeatTask(), delay, period);
}
}
class HeartBeatTaskextends TimerTask {
public void run() {
sock.write("H");
}
Will the second approach be granted higher priority?
Firstly, your Thread-based idiom will not schedule at fixed rate without an infinite loop.
That's one disadvantage too: you probably want to set some condition to exit the loop.
You also need to catch InterruptedException when invoking static Thread.sleep.
Another popular idiom for scheduled execution is by using a ScheduledExecutorService.
Find the 3 alternatives below:
Timer
// says "foo" every half second
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
System.out.println("foo");
}
}, 0, 500);
Pros: simple
Cons:
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up."
Docs here.
Infinite loop
new Thread() {
#Override
public void run() {
while (true) {
// Says "blah" every half second
System.out.println("blah");
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
// nope
}
}
}
}.start();
Pros: super simple. You can vary your recurring delay programmatically.
Cons: Thread.sleep is still
subject to the precision and accuracy of system timers and schedulers.
... and requires catching InterruptedException.
Docs here.
Also:
your infinite loop might require a (somehow potentially cumbersome) breaking condition
no initial delay setting unless applied manually before infinite loop, which would require another try / catch.
Executors
ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor();
es.scheduleAtFixedRate(
new Runnable() {
#Override
public void run() {
// Says "bar" every half second
System.out.println("bar");
}
},
0, 500, TimeUnit.MILLISECONDS);
Pros: this is the most recent feature of the 3. Very simple and elegant - you can also schedule Callables (not at fixed rate though) and re-use the ExecutorService. The documentation for java.util.Timer actually mentions ScheduledThreadPoolExecutor (implementing the ScheduledExecutorService interface) as a "more versatile replacement for the Timer/TimerTask combination".
Cons as documented:
If any execution of this task takes longer than its period, then subsequent executions may start late,
Docs here.
Yes, I don't know how timers are implemented internally, but what I do understand here is, if you use sleep, you will have to handle InterruptedException, and eating up that exception may not be a good practice. moreover timer tasks would be running within its thread space, and you have better control over it.
You can stop the timer any time if you want, In this case, you may not be able to do that
If you use the sleep approach, there are some issues to consider.
One is that the sleep time isn't exact, and you could have drift over time (maybe while your thread is sleeping another application hogs CPU and it takes longer than expected for your thread to send its heartbeat, now the next time the thread sends a heartbeat is delayed), your sleep time will be augmented by various things incrementally (you won't sleep for less than your sleep time but may frequently sleep for a bit more), and those increments will add up over time.
Another is that you could have a problem with the socket, you would have to write code to handle making a new connection.
The thread would need to be well-behaved and respond to interruption, or else be a daemon thread. If it had to share data across threads you'd need to be aware of memory visibility issues.
Using a timer would mean each launching of a task would have a fresh start and you wouldn't be vulnerable to accumulated delays or stale network connections.

Does Thread.sleep(milis) function make all Threads sleep?

I have a code fragment from a "Runnable" class is like that:
public void run() {
//Do some stuff
while(!someCondition){
//Do some stuff
while(anotherCondition){
try {
Thread.sleep(60000);
}catch (InterruptedException e){
logger.error(e.getMessage());
e.printStackTrace();
}
//Do some stuff
}
threadExecutor = Executors.newCachedThreadPool();
RunnableClass rc = new RunnableClass();
Thread rcThread = new Thread(rc);
rcThread.setDefaultUncaughtExceptionHandler(new SomeUncaughtExHandler());
threadExecutor.execute(rcThread);
}
//Do some stuff
}
Does calling Thread.sleep(60000); cause all of RunnableClass Threads to sleep or not?
Thread.sleep() makes the current thread sleep. This is spelled out in the Javadoc:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
Thread.sleep() only makes the calling thread sleep.
Thread.sleep() makes the current thread sleep; but it is bit confusing. This is why, now; the suggested way is to use TimeUnit sleep method. This API got added in Java SE5 version.
TimeUnit.SECONDS.sleep(5);
Javadoc :
Performs a Thread.sleep using this unit. This is a convenience method that converts time arguments into the form required by the Thread.sleep method.
Also you can use different units like SECONDS, MILLISECONDS etc to avoid any confusion on the unit of argument passed inside sleep method.
According to the manual:
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds
So no, it doesn't effect all threads.
No, only the current thread sleeps. According to the documentation:
Causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds
Thread.sleep(x)
causes the current thread to (sleep) suspend execution for a ‘x ‘ ms. This is an efficient means of making processor time available to the other threads of your application or other applications on your system.

question related with java

Can you please suggest how to use until command in Java, actually I have to perform this System.exit(0); after 3 second of current system time. So I am thinking to do by long time=System.currentTimeMillis();
until(System.currentTimeMillis()<(time+3000))
{
System.exit(0);
}
But it reports an error
Actually java does not have an until command but you should use a while-loop or a do-while-loop instead.
Note: Thread.sleep(3000); would be a better way to sleep for three seconds.
I might have misunderstood your requirement but if you just want to wait for 3 seconds then call System.exit(0), you can just use:
Thread.sleep(3000);
System.exit(0);
I apologise if I have misunderstood your question.
If you're trying to wait for a specific period of time constantly polling on the elapsed system time is not the way to go. Alternatively you can use the thread scheduler to pause execution of the current thread and request that the JVM notify you when the time is up. This allows other threads in a multithreaded environment to get things done while you wait.
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
// Insert appropriate exception handling here...
}
Thread.sleep makes the currently executing thread move to the ready state for 3000ms. The JVM is then responsible for moving the thread back to the running state when at least 3 seconds is up.

Categories

Resources