Java: How to make a new thread every second - java

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);
}
}

Related

How to schedule a periodic task but stop and return result if a condition is fulfilled (Java)

I need to execute a certain task periodically within a certain timeout.
But dependent on the result of the task, I want to stop before the end of the timeout is reached. And in addition I need a reference to the currently executed task in order to have the chance to ask for the result.
Solution to 1) is no problem, because it can be solved with the little code snipped shown below. But I can not figure out how to integrate 2). So with this code example, I would like that the beeper object runs code which can have a positive or a negative result and based on (for example) a positive result, the beeper task should no longer be executed periodically.
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
In your run method if condition is fulfilled then invoke scheduler.shutdown(). That should do exactly what you want.
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() {
System.out.println("beep");
if(isMyCondition() {
scheduler.shutdown();
}
}
};
See javadoc for ExecutorService.shutdown()

Run an exe file using java in background [duplicate]

I want to spawn a Java thread from my main java program and that thread should execute separately without interfering with the main program. Here is how it should be:
Main program initiated by the user
Does some business work and should create a new thread that could handle the background process
As soon as the thread is created, the main program shouldn't wait till the spawned thread completes. In fact it should be seamless..
One straight-forward way is to manually spawn the thread yourself:
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
new Thread(r).start();
//this line will execute immediately, not waiting for your task to complete
}
Alternatively, if you need to spawn more than one thread or need to do it repeatedly, you can use the higher level concurrent API and an executor service:
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
runYourBackgroundTaskHere();
}
};
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(r);
// this line will execute immediately, not waiting for your task to complete
executor.shutDown(); // tell executor no more work is coming
// this line will also execute without waiting for the task to finish
}
Even Simpler, using Lambda! (Java 8) Yes, this really does work and I'm surprised no one has mentioned it.
new Thread(() -> {
//run background code here
}).start();
This is another way of creating a thread using an anonymous inner class.
public class AnonThread {
public static void main(String[] args) {
System.out.println("Main thread");
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Inner Thread");
}
}).start();
}
}
And if you like to do it the Java 8 way, you can do it as simple as this:
public class Java8Thread {
public static void main(String[] args) {
System.out.println("Main thread");
new Thread(this::myBackgroundTask).start();
}
private void myBackgroundTask() {
System.out.println("Inner Thread");
}
}

how to execute certain tasks in intervals(task schedular)

I have some type of task for example in a loop with same method but different arguments,
I need to execute these tasks in one after another in some intervals,
and all this activity need to be execute in again and again in a particular schedule,
e.g. let say I have a method called
public void GetData(String tablename){
}
so first time I will provide table1 then table2 then table3.....
similar to for loop but need some interval in between,
and same above all execution need to execute in each 10 min,
sample code I have implemented as
final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
final Runnable runner = new Runnable() {
public void run() {
getData(String table);
}
};
final ScheduledFuture<?> taskHandle =
scheduler.scheduleAtFixedRate(runner, 1, 10, SECONDS);
its working fine for one table for need help and best way to implement for multiple tables.
tryjava.util.Timer to schedule a task to execute
public class ReminderBeep {
Toolkit toolkit;
Timer timer;
public ReminderBeep(int seconds) {
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
toolkit.beep();
//timer.cancel(); //Not necessary because we call System.exit
System.exit(0); //Stops the AWT thread (and everything else)
}
}
public static void main(String args[]) {
System.out.println("About to schedule task.");
new ReminderBeep(5);
System.out.println("Task scheduled.");
}
}
You can just use Thread.sleep() in your loop (if it's not on the main thread). Something like this (the code is not tested so may contain errors):
ExecutorService executorService = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
public void run() {
getData(String table);
}
Thread.sleep(10000);
}

What is the simplest way in java to run many methods in separate threads and wait until all will be finished?

I want a method that runs 2 or more methods in separate threads. I want be sure that method won't finish before all threads are done.
The best approach is to utilize the Executor Service API to manage a thread pool instead of starting an open-ended number of threads on your own.
ExecutorService pool = Executors.newCachedThreadPool();
for (Runnable r : new Runnable[] {
new R() { void r() { myMethod1(); }},
new R() { void r() { myMethod2(); }},
})
pool.execute(r);
pool.shutdown();
pool.awaitTermination(60, TimeUnit.SECONDS);
abstract class R implements Runnable
public final void run() { r(); }
abstract void r();
}
Note that it is not advisable to insist on every method running in its own, separate thread. Threads are quite heavyweight (each allocating a complete call stack) and performance actually decreases as the thread count increases far beyond the number of available processor cores.
I prefer something like this:
public static void runParallel(Runnable... runnables) throws InterruptedException {
final CountDownLatch done = new CountDownLatch(runnables.length);
for (final Runnable r: runnables) {
new Thread(new Runnable() {
public void run() {
try {
r.run();
} finally {
done.countDown();
}
}
}).start();
}
done.await();
}
An advantage of this approach is that it also works with thread pool (i.e. you can replace new Thread(...).start() with executor.submit(...)).
Also it allows you to use pre-existing thread pool, unlike solutions based on awaitTermination() that force you to create new pools for each invocation.
My solution is
Function:
public void runParallel(Runnable... runnables) throws InterruptedException {
List<Thread> threads = new ArrayList<Thread>(runnables.length);
for (Runnable runnable :runnables) {
Thread th = new Thread(runnable);
threads.add(th);
th.start();
}
for (Thread th : threads) {
th.join();
}
Use:
runParallel(new Runnable() {
#Override
public void run() {
method1()
}
}, new Runnable() {
#Override
public void run() {
method2()
}
}
);
any better ideas? Maybe there is a shorter way that I'm not aware of ;)
Following the API given by damienix:
public void runParallel(Runnable... runnables) throws InterruptedException {
final ExecutorService pool = Executors.newFixedThreadPool(runnables.length);
for (Runnable runnable: runnables) {
pool.submit(runnable);
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.MINUTES);
}

Java delay method run

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.

Categories