Java delay method run - java

I need to run some code after a period of time without blocking the current method.
I tried the following 2 approaches:
public static void main(final String[] args) {
System.out.println("Start");
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
System.out.println("done");
this.cancel();
}
}, 4000L);
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(new Runnable() {
public void run() {
System.out.println("done");
}
}, 2, TimeUnit.SECONDS);
executor.shutdown();
System.out.println("Stop");
}
The problem is that the first does block the app and the second does not allow main to exit until it finishes;
How to run the code after some time and exit the current method right after scheduling it ?

You could create a own thread and set it as Daemon:
final Thread myThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(20000);
} catch (final InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("20 seconds over");
}
});
myThread.setDaemon(true);
myThread.start();
An alternative is to create the Executor with a ThreadFactory, in which you set the created Thread as Daemon. You have to use these function:
Excecutors.newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory)

If you want the job you create to outlive the java process that created it, then you will have to launch another process. Commons exec can help with that, since launching a process from java is not as simple as it may first appear.
If you set the thread as daemon then your process exits, then the daemon thread will also be killed - its address space is gone.

Use a ScheduledExecutor

Use a scheduled executor:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html
It has a schedule method, a schedule at fixed rate method and a schedule with fixed delay method.

Related

How to cancel incomplete task on ExecutorService [duplicate]

This question already has answers here:
Java ExecutorService pause/resume a specific thread
(3 answers)
Closed 5 years ago.
I have submitted two tasks, task1 & task2 to the ExecutorService. Task2 needs 5 seconds to complete, and task1 need 10 seconds.
How can I stop the task(s) submitted (ie: task1) when task2 completes and continues the rest of logic?
Here's my code so far:
public class mt_poc {
public static void action_1 () throws InterruptedException {
System.out.println("action_1 invoke " );
Thread.sleep(10000);
action_2 ();
System.out.println("action_1 done" );
}
public static void action_2() throws InterruptedException {
System.out.println("action_2 invoke " );
Thread.sleep(5000);
System.out.println("action_2 done " );
}
public static void main(String[] args) {
System.out.println("TEST");
Runnable task1 = new Runnable() {
public void run() {
try {
action_1 ();
}
catch(InterruptedException e) {
System.out.println("action_1 invoke interrupted");
}
System.out.println("action_1 invoke run is over" );
}
};
Runnable task2 = new Runnable() {
public void run() {
try {
action_2 ();
}
catch(InterruptedException e) {
System.out.println("action_2 invoke interrupted");
}
System.out.println("action_2 invoke run is over" );
}
};
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
executor.submit(task1);
executor.submit(task2);
// cancel uncomplete task
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
// continues the rest of logic
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Shutdown executor");
}
}
you can use shutdownNow() method
Attempts to stop all actively executing tasks, halts the processing of
waiting tasks, and returns a list of the tasks that were awaiting
execution.
for full documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
shutdown() method will wait for all the threads to finish before closing the executor
You have to retrieve the Future objects from the submit function.
These are used to control the running thread and get the status of it.
If you have the futures, call Future2.get(). This will block the thread until the Task2 is finished. No you can use Future1.cancel(true) to abort the other thread.
But pausing and resuming is not possible. See Java ExecutorService pause/resume a specific thread
If you want such specific behaviour you need to use Threads.
But why you want to do this in seperate Threads as it would be much simpler and efficient t use a single one.

Java: How to make a new thread every second

I have a thread in Java that makes a web call and stores the information retrieved, but it only retrieves information for that particular instant. I'd like to run this thread every second for a certain period of time to get a better view of the data. How can I do this? I've looked at ScheduledExecutorService, and from what I can tell if the thread is still running when it's time to set up the next run, it waits until the first thread is complete, which isn't what I'm looking for.
You can do this by a double schedule. Use scheduleWithFixedDelay() to set off a job every second. This job starts the method which you really want to run. Here is some code based on Oracle's ScheduledExecutorService API.
The Thread.sleep() is there to simulate a long-running task.
class Beeper {
public static void main(String[] args) {
(new Beeper()).beep();
}
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public void beep() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
final Runnable beeper2 = new Runnable() {
public void run() {
(new Thread(beeper)).start();
}
};
final ScheduledFuture<?> beeperHandle = scheduler.scheduleAtFixedRate(beeper2, 1, 1, SECONDS);
}
}
What you need is the scheduleAtFixedRate method: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledExecutorService.html#scheduleAtFixedRate(java.lang.Runnable,%20long,%20long,%20java.util.concurrent.TimeUnit)
When the scheduler waits until the first thread is complete, it's because you're using scheduleWithFixedDelay.
However, if you absolutely want the threads run concurrently, you should try this:
pool.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
pool.submit(myJob);
}
}, 1, 1, TimeUnit.SECONDS);
I advise to always use a pool.
What about this?
public static void main (String [] args) throws InterruptedException{
ExecutorService executorService =
Executors.newFixedThreadPool(10);
while (true){
executorService.submit(new Runnable() {
#Override
public void run() {
// do your work here..
System.out.println("Executed!");
}});
Thread.sleep(1000);
}
}

How to stop a thread as soon as a certain amount of time expires? [duplicate]

This question already has answers here:
How to properly stop the Thread in Java?
(9 answers)
Closed 9 years ago.
I am having a problem trying to stop a thread instantly after a certain amount of time has elapsed, because thread.stop and similar others have been depreciated.
The thread that I am trying to stop uses my mouse and I need to stop it so that I can use my mouse in other ways.
What I was thinking is the code below, which was just to make another thread to watch how long the main thread has been running and if it is alive, stop it, but I can't accomplish this.
public void threadRun(int a) {
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
// does things with mouse which may need to be ended while they
// are in action
}
});
Thread watchThread = new Thread(new Runnable() {
#Override
public void run() {
if (timeFromMark(mark) > a) {
if (mainThread.isAlive()) {
// How can I stop the mainThread?
}
}
}
});
}
You need to define a class for your second thread that extends runnable and pass the first thread as an argument.
Then you can stop the first thread.
But instead of doing this manually, have a look at the Java ThreadPoolExecuter and its awaitTermination(long timeout, TimeUnit unit) method. (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html )
Will save a lot of work.
ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("doing stuff");
Thread.sleep(10000);
System.out.println("finished");
} catch (InterruptedException e) {
System.out.println("Interrupted before finished!");
}
}
};
executor.execute(r);
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdownNow();
} catch (InterruptedException e) {
//
}
System.out.println("Thread worker forced down. Continue with Application...");
Produces:
doing stuff
Interrupted before finished!
Thread worker forced down. Continue with Application...
Last two messages are nearly equal in terms of time and may change positions (its two different threads, continuing)
Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).
Taken from How do I kill a thread from another thread in Java?
Killing/stopping threads is a bad idea. That's why they deprecated those methods. It's better to ask the thread to stop. E.g., something like the example below. (But note: if "do_something()" takes a long time, then you might want to use an interrupt to abort whatever it is.)
import java.util.concurrent.atomic.AtomicBoolean;
public class Stoppable {
private AtomicBoolean timeToDie = new AtomicBoolean(false);
private Thread thread;
public void start() {
if (thread != null) {
throw new IllegalStateException("already running");
}
thread = new Thread(new Runnable() {
public void run() {
while (!timeToDie.get()) {
// do_something();
}
}
});
thread.start();
}
public void stop() throws InterruptedException {
timeToDie.set(true);
thread.join();
thread = null;
}
}

Java code Multiple Thread, Wait to start other

I a trying to find out, after complete first thread completely than start second thread, after complete second thread than start third thread, Please help me!!
Here is my code:
public class wait {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("First Thread");
createtheard2();
}
public static void createtheard2() {
try {
System.out.println("Second Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
createtheard3();
}
public static void createtheard3() {
try {
System.out.println("Third Thread");
} catch(Exception error1) {
error1.printStackTrace();
}
}
}
After complete first thread, than start second thread, after complete second thread, than start third thread, Please help me!! Thanks!!
Implement Runnable
public class ThreadDemo implements Runnable {
public void run() {
//Do this what you need
}
}
Use join to wait while thread will be completed.
Thread t1 = new Thread(new ThreadDemo());
// this will call run() function
t1.start();
// waits for this thread to die
t1.join();
Thread t2 = new Thread(new ThreadDemo());
// this will call run() function
t2.start();
// waits for this thread to die
t2.join();
From http://docs.oracle.com/javase/tutorial/essential/concurrency/join.html
t.join() causes the current thread to pause execution until t's
thread terminates.
In your case paused by join method invocation thread will be Main thread.
I think what you need is if task 1 (thread in your terms) success, run task2 else wait for task1. consider the following.
public class Process{
public static void runProcess1() {
boolean done = false;
do {
// make done=true after task1 is done
} while (done);
runProcess2();
}
public static void runProcess2() {
boolean done = false;
do {
// make done=true after task2 is done
} while (done);
runProcess3();
}
public static void main(String[] args) {
runProcess1();
}
}
As it was pointed out, using threads in this case does not make sense as you are executing tasks sequentially.
However, it is possible to have a single thread running at a time with SingleThreadExecutor
For example, you
Add your threads to a "todo list" (ArrayList will do the job)
Schedule a task (ExecutorService.execute())
Wait for the scheduled task to complete (Thread.join())
Drop the thread from the "todo list" tasks.remove(currentTask);
Pick the next task or go to step 7 if all has been finished
Go back to step 2
Kill the ExecutorService (ExecutorService.shutdown())
Alternatively, you could use ExecutorService.invokeAll() using a single thread executor.
You could even simply run the tasks directly in a loop, invoking start(), however, I'd really recommend against using concurrency where it is not a necessity.

Run thread only for one minute in java

What the best practice to run thread only for some period?
I can easily check curentTime and close the thread after in worked for some time, but I think it's not the right way.
It depends on what you want to achieve, but generally speaking the approach you mentioned with measuring the time from the start is not that wrong.
I would code it like this:
private static class MyTimerTask extends TimerTask {
private final Thread target;
public MyTimerTask(Thread target) { this.target = target; }
public void run() {
target.interrupt();
}
}
public void run() {
Thread final theThread = Thread.currentThread();
Timer timer = new Timer();
try {
timer.schedule(new MyTimerTask(theThread), 60000});
while(!theThread.interrupted()) {
....
}
} finally {
timer.cancel();
}
}
... which is Hovercraft described, except using interrupt instead of an ad-hoc flag. Using interrupts has the advantage that some I/O calls are unblocked by an interrupt, and some libraries will respect it.
I'm surprised (and deeply disappointed) that no one has mentioned the Executors framework. It has usurped the Timer framework (or at least the java.util.Timer class) as the "goto" for scheduled tasks.
For instance,
// Start thread
final Thread t = new Thread(new Runnable(){
#Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
try{
// do stuff
}
catch(InterruptedException e){
Thread.currentThread().interrupt();
}
}
}
});
t.start();
// Schedule task to terminate thread in 1 minute
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.schedule(new Runnable(){
#Override
public void run(){
t.interrupt();
}
}, 1, TimeUnit.MINUTES);

Categories