I was wondering which would be the most efficient approach to implement some kind of background task in java (I guess that would be some kind of nonblocking Threads). To be more precise - I have some java code and then at some point I need to execute a long running operation. What I would like to do is to execute that operation in the background so that the rest of the program can continue executing and when that task is completed just update some specific object which. This change would be then detected by other components.
You want to make a new thread; depending on how long the method needs to be, you can make it inline:
// some code
new Thread(new Runnable() {
@Override public void run() {
// do stuff in this thread
}
}).start();
Or just make a new class:
public class MyWorker extends Thread {
public void run() {
// do stuff in this thread
}
}
// some code
new MyWorker().start();
You should use Thread Pools,
http://java.sun.com/docs/books/tutorial/essential/concurrency/pools.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With