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.
Related
For example I have some code block which takes more than 30 seconds to execute but I want to stop that if it takes more than 30 seconds. I am trying with executor.shutdown(), executor.awaitTermination(30, TimeUnit.SECONDS) and executor.shutdownNow(); but i can not understand where I have to write my code block which I want to terminate after a specific time. Please give an perfect example.
It is pretty simple: when using threads there is no reliable way to kill that thread ( see here for example).
The only choice: start another JVM in another process - because that you can actually kill. See here for details.
Of course - this is rather not the way to go. A better way would be to implement your long-running-task in a way that regularly checks for "cancel" commands for example.
The way to go with your methods mentioned, you just add your task to the executor, then in the next line of code put executor.shutdown(); It restricts your executor from taking other tasks and then your actually put executor.awaitTermination(30, TimeUnit.SECONDS) to set the "timer" to wait for the task to complete during this time
A simple samle code snipet:
ExecutorService taskExecutor = Executors.newFixedThreadPool(1);
taskExecutor.execute(new MyTask());
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
...
}
I'm writing a sort of tutorial about programming (it will be a Java repo on github) where users can clone the repo and write their own code inside empty methods to solve algorithmic problems. After they write their code, they can launch unit tests to check if their solution is correct and if it completes execution in less than a certain time (to assure they found the most efficient solution).
So my repo will contain a lot of classes with empty methods and all the non-empty unit tests to check the code the users will write.
What I'm doing in the JUnit tests is something like that:
// Problem.solveProblem() can be a long running task
Thread runner = new Thread(() -> Problem.solveProblem(input));
runner.start();
try {
Thread.currentThread().sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
if (runner.isAlive()) {
fail("Your algorithm is taking too long.");
runner.stop();
}
Now, if a user writes a not optimized algorithm, the test fails correctly, but the runner thread will continue to run (and so will do the test thread) until it terminates, which can happen after minutes, though I call running.stop(). So I have tests that can last minutes instead of seconds like I'd like.
I know how to gracefully kill a thread in Java, but in this case I don't want the users to take care of multithreading issues (like checking/updating shared variables): I just want them to write only the code to solve the problem.
So my question is: is there a way to abruptly kill a thread in Java? If not, is there any other approach I could follow to accomplish my goal?
Thanks,
Andrea
You can use a ScheduledExecutorService with a timeout:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Future<?> future = executor.schedule(() -> Problem.solveProblem(input));
try {
future.get(500, TimeUnit.MILLISECONDS);
} catch (Exception e){
fail("Your algorithm is taking too long.");
future.cancel(true);
}
Will probably require some refinements but you get the basics.
Use Thread.currentThread().getThreadGroup() to iterate through. Thread.stop is the brute-force way, but in your case it'll probably work if you call Thread.interrupt -edit- I read this too quickly and thought you were calling sleep in your spawned threads. Rereading, I see that you are just doing this in your main thread, so as RealSkeptic commented on this post it is uncertain and probably unlikely that interrupt will solve the problem
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.
I am writing a GUI for a program that takes some inputs and runs an algorithm on them. The code for the algorithm is fairly long and complex so I have just been launching a new thread from the GUI in order to perform the computations on the inputs.
//algorithmThread previously initialized
if(e.getSource() == startButton) {
if(update.updateStrings(textFields)) {
algorithmThread.start();
}
}
We want to add functionality that will allow the user to stop the computation (it runs for about half an hour on my laptop before producing a result) in the case that they have provided the wrong input files. This is how I am handling that.
else if(e.getSource() == stopButton) {
//if the user presses the stop button then intterupt the
//thread running the algorithm
algorithmThread.interrupt();
System.out.println("algorithm stopped"); //debugging code
//recreate the thread in case the user hits the start button again
algorithmThread = new Thread() {
public void run() {
runNOC();
}
};
}
The program does successfully stop the algorithm(although I think I should do some exception handling), allow the user to enter new input, and restart. My question is, under what conditions would I have to check Thread.interrupted() in the code for the algorithm? Is it necessary/best practice? Or is it acceptable to stop a thread in the manner illustrated above?
All the Thread.interrupt() method does is set an "interrupted" flag, so stopping a thread in this manner requires its cooperation. For example, the algorithm should poll the interrupt status every once in a while, for example once per iteration. You can see an example of this in the Java concurrency tutorial.
Since you are working with a GUI, you may find it easier to run the background thread using a SwingWorker. This class has many features convenient for GUI programming, like updating the GUI when the computation has finished using the done method and canceling the computation without using Thread.interrupt(). Canceling in this manner still requires cooperation from the thread, but is safer because interrupting a thread causes an InterruptedException to be thrown in some situations, such as when the thread is sleeping in Thread.sleep or waiting on a lock in Object.wait.
interrupt is not always evil following this thread:
Is Thread.interrupt() evil?
Around here, we use this method in one specific place: handling
InterruptedExceptions. That may seem a little strange but here's what
it looks like in code:
try {
// Some code that might throw an InterruptedException.
// Using sleep as an example
Thread.sleep(10000);
}
catch (InterruptedException ie) {
System.err.println("Interrupted in our long run. Stopping.");
Thread.currentThread().interrupt();
}
This does two things for us:
It avoids eating the interrupt exception. IDE auto-exception handlers
always provide you with something like ie.printStackTrace(); and a
jaunty "TODO: Something useful needs to go here!" comment.
It restores
the interrupt status without forcing a checked exception on this
method. If the method signature that you're implementing does not have
a throws InterruptedException clause, this is your other option for
propagating that interrupted status.
Every 3 seconds, I want the server to send a message.
To do this, I have this code.
try {
Thread.sleep(3500);
getPackets().sendGameMessage("[Server Message]: Remember to vote!");
} catch (InterruptedException e) {
e.printStackTrace();
}
The code works of course, waits 3 and a half seconds, sends the message.
But how can I make it loop, so every 3 and a half seconds, it will send it without stopping?
I'm a bit surprised that someone tackling networking in Java doesn't know how to put code in an infinite loop. Thus, I wonder if your real question is "is there a better way?"
To that question, I would say that you should consider using either java.util.Timer to send the message, or using scheduleAtFixedRate() from a ScheduledExecutorService obtained from Executors.newScheduledThreadPool().
The best way is to use a Timer. See Java how to write a timer
spawn the above code in a separate thread and enclose it within a while(true) loop.
This kind of code is not very useful because it blocks the current thread and also seems to unnecessarily clutter the program logic. It's better to delegate it to a worker thread that executes the send in the background. Also Thread.sleep is known to be inaccurate.
As of the latest Java versions, I think the most elegant way to do it is using ScheduledThreadPoolExecutor:
ScheduledThreadPoolExecutor executor = new ScheduledThraedPoolExecutor(1);
executor.scheduleWithFixedDelay(new Runnable() {
public void run() {
getPackets().sendGameMessage("[Server Message]: Remember to vote!");
}
}, 0, 3500, TimeUnit.MILLISECONDS);
Also you don't have to worry about that annoying InterruptedException.