I have 6 functions which I need to run in specific time intervals:
public void runFirst() {
System.out.println("First method");
}
public void runSecond() {
System.out.println("Second method");
}
public void runThird() {
System.out.println("Third method");
}
public void runFourth() {
System.out.println("Fourth method");
}
public void runFifth() {
System.out.println("Fifth method");
}
public void runSixth() {
System.out.println("Sixth method");
}
I need to run "first" as soon as i click the button, second must be after 65 seconds, third 20 seconds after second, fourth 15 seconds after the third one and so on, at the time i'm using Thread.sleep but i will need to make it without sleeps.
What is the best way and can someone show me some example based on my methods.
you can use Quartz. While clicking the button you can get system current time and add a new scheduled job to run on specific date&time. So Quartz will handle it to run on the time.
Another way is to create a new Thread and define on it the sleep period of time and let that to run function.
Why cant you use
Thread.sleep
and run this code in different thread (then, the whole app wont stop on sleep)
Maybe you want to check the #wait(timeout) method, the one with timeout.
Quote:
"... the thread lies dormant until the specified amount of real time
has elapsed..."
To run a task after some time, you should use a Timer, which is a "A facility for threads to schedule tasks for future execution in a background thread. ".
It frees you from creating your own thread : less error-prone and easier. It can manage several scheduled tasks. Beware though, these task should be short-lived (other they will block the thread used for scheduling puropose by the timer)..
Use a ExecutorService. The basic idea would be something like this:
// "Global" resource
final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(5); // Adjust threadpool size
...
// inside onclick() processing
ScheduledFuture<Void> future1 = executorService.schedule(new Callable<Void>() {
#Override Void call() {
try {
runFirst();
} finally {
scheduleFuture2();
}
}
},
65,
TimeUnit.SECONDS);
...
void scheduleFuture2() {
ScheduledFuture<Void> future2 = executorService.schedule(new Callable<Void>() {
#Override Void call() {
try {
runSecond();
} finally {
scheduleFuture3();
}
}
},
20,
TimeUnit.SECONDS);
}
...
void scheduleFuture3() {
ScheduledFuture<Void> future3 = executorService.schedule(new Callable<Void>() {
#Override Void call() {
try {
runThird();
} finally {
scheduleFuture4();
}
}
},
15,
TimeUnit.SECONDS);
}
...
// And so on
Some notes:
if runFirst() , runSecond(), ... perform Swing / AWT UI operations, the you should proably make use of SwingUtilities.invokeLater inside those methods
don't forget to invoke executorService.shutdown() when you not going to use this mechanism anymore. If you forget about it, you will "leak" threads.
The references to Void above (uppercase "V") are intentional: we are using the Void class and not the void type
Use a ScheduledExecutorService!
{
ScheduledExecutorService worker = Executors.newScheduledThreadPool(1);
worker.execute(() -> runFirst());
worker.schedule(() -> runSecond(), 65, TimeUnit.SECONDS);
worker.schedule(() -> runThird(), 85, TimeUnit.SECONDS);
worker.schedule(() -> runFourth(), 100, TimeUnit.SECONDS);
worker.schedule(() -> runFifth(), 110, TimeUnit.SECONDS);
worker.schedule(() -> runSixth(), 115, TimeUnit.SECONDS);
worker.shutdown();
}
If you cannot use Java 8 for some reason, use anonymous implementations of Runnable instead of Lambda expressions:
// worker.schedule(() -> runSixth(), 115, TimeUnit.SECONDS);
worker.schedule(new Runnable(){
#Override
public void run() {
runSixth();
}}, 115, TimeUnit.SECONDS);
Create a Thread class and another Class for your methods
Now:
public class ThreadTest implements Runnable {
private int functionNumber;
private int time2start;
private YourClass obj;
public ThreadTest(int functionNumber, int time2start, YourClass obj) {
this.functionNumber = functionNumber;
this.time2start = time2start;
this.obj = obj;
}
public void run() {
try {
Thread.currentThread().sleep(time2start);
} catch (Exception ex) {
}//Time Delay before executing methods
switch (functionNumber) {
case 1:
obj.runFirst();
break;
case 2:
obj.runSecond();
break;
case 3:
obj.runThird();
break;
case 4:
obj.runFourth();
break;
//keep adding
}
}
}
then Class for your methods :
public class YourClass {
public void runFirst() {
System.out.println("First method");
}
public void runSecond() {
System.out.println("Second method");
}
public void runThird() {
System.out.println("Third method");
}
public void runFourth() {
System.out.println("Fourth method");
}
public void runFifth() {
System.out.println("Fifth method");
}
public void runSixth() {
System.out.println("Sixth method");
}
}
Now this is the method for onClick event for the button:
//on button click
ThreadTest th1 = new ThreadTest(1, 0, obj);//here obj is YourClass
ThreadTest th2 = new ThreadTest(2, 65000, obj);//65 SECONDS
//... keep adding
Thread thread1 = new Thread(th1);
Thread thread2 = new Thread(th2);
//...keep adding
thread1.start();
thread2.start();
//...keep adding
Related
I've a core method in my project which I need it to be synchronized in order not to be accessed twice at the same time, and hence I have a thread which uses an instance from this class to access this method, but inside this thread I need to have a long life loop to be used to access the same method with a fixed value so I have to use another thread in order to allow the first thread to move on and complete it's duties, but for sure the method doesn't run from that second thread using the same instance used in the first thread, and somehow I can't instantiate another instance from the class as I have to use this instance exactly, so how to overcome this problem.
below is the problem translated to java:
public class ClassOne {
synchronized public void my_method(int number) {
// Do some Work
}
}
public class ClassTwo {
private void some_method() {
Thread one = new Thread(new Runnable() {
#Override
public void run() {
ClassOne class_one = new ClassOne();
// DO Work
class_one.my_method(0);
run_loop(class_one);
// Complete Work
}
});
one.start();
}
boolean running = true;
private void run_loop(final ClassOne class_one) {
Thread two = new Thread(new Runnable() {
#Override
public void run() {
while (running) {
class_one.my_method(1); // won't run
Thread.sleep(10000);
}
}
});
two.start();
}
}
Actual problem overview:
my_method --- > is to send UDP packets.
the method has to be synchronized otherwise I'll get the socket is already open exception when trying to use it more than once repeatedly.
at some point, I have to send a KeepAlive message repeatedly each 10 seconds, so, I have to launch a separate thread for that which is thread two in run_loop method.
Putting something that will compile and work. I don't see why you need this function to be synchronized. Check the output for this program...The second thread access this method only when the first thread is done accessing (unless you have missed adding some additional code).
class ClassOne {
int criticalData = 1;
synchronized public void my_method(int number) {
// Do some Work
criticalData *= 31;
System.out.println("Critical data:" + criticalData + "[" + Thread.currentThread().getName() + "]");
}
}
class ClassTwo {
boolean running = true;
public void some_method() {
Thread one = new Thread(new Runnable() {
public void run() {
ClassOne class_one = new ClassOne();
// DO Work
class_one.my_method(0);
run_loop(class_one);
// Complete Work
}
});
one.start();
}
public void run_loop(final ClassOne class_one) {
Thread two = new Thread(new Runnable() {
public void run() {
while (running) {
class_one.my_method(1); // won't run
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
two.start();
}
}
public class StackExchangeProblem {
public static void main(String[] args) {
ClassTwo two = new ClassTwo();
two.some_method();
}
}
I have a class with a method that blocks and would like to validate that it is blocking. The method is as shown below.
public static void main(String[] args) {
// the main routine is only here so I can also run the app from the command line
applicationLauncherInstance.initialize();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if (null != application) {
applicationLauncherInstance.terminate();
}
}
});
try {
_latch.await();
} catch (InterruptedException e) {
log.warn(" main : ", e);
}
System.exit(0);
}
How can I write a unit test for such a method. I am stuck before starting.
public class ApplicationLauncherTest extends TestCase {
public void testMain() throws Exception {
ApplicationLauncher launcher = new ApplicationLauncher();
}
}
Thanks to Kulu, I found the solution.
public void testMain() throws Exception {
Thread mainRunner = new Thread(() -> {
ApplicationLauncher.main(new String[]{});
});
mainRunner.start();
Thread.sleep(5000);
assertEquals(Thread.State.WAITING, mainRunner.getState());
mainRunner.interrupt();
}
Bwire's answer is a good way there, but I highly recommend that no
one ever use Thread.sleep() in unit tests for validation of some situation. It's impossible to get the timing right:
If it's too short, you'll get a lotta false results (random failures, yay)
If it's too long, you end up creating painfully slow tests over time. Don't underestimate this.
So, what's the answer? Any time you need to "sleep" to test something, instead "wait" for that to be true (constantly checking). This way:
As soon as the condition is true, your program resumes--no wasted time.
You can set the timeout on this "wait" to a crazy large value, to avoid random failures.
Here's a modified version of Bware's self-response...
public void testMain() throws Exception {
Thread mainRunner = new Thread(() -> {
ApplicationLauncher.main(new String[]{});
});
mainRunner.start();
expectToBlock(mainRunner, 30, TimeUnit.SECONDS);
mainRunner.interrupt();
}
private static void expectToBlock(Thread thread, long waitCount, TimeUnit waitUnits) {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < waitUnits.toMillis(waitCount)) {
if (thread.getState() == Thread.State.WAITING) {
return;
}
Thread.sleep(50); // Don't hog the CPU
}
Assert.fail("Timed out while waiting for thread to block");
}
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);
}
}
I am new to the Threading, so if please give me an advice for my case.
I would like create a new thread to do something and I don't care this thread can do complete or not.
I intend to use ExecutorCompletionService to do my job but this class is not suitable for me. It must call take or poll to drain a queue to avoid memory leak. So, this means I must wait until the thread complete. I read this from this question
This is the current code
ExecutorService executor = Executors.newCachedThreadPool();
CompletionService<Entity> completion = new ExecutorCompletionService<>(executor);
DoSomeThingClass doSomething = getInstance();
completion.submit(doSomething);
executor.shutdown();
// Continue to do other job and I don't care whenever doSomeThing is complete.
// However when doSomeThing finish, I don't need to do anything to avoid memory leak
For that reason, please give me an approach for my case and some skeleton code for example.
Thank you so much
You can mark this thread as "Daemon". And when your main thread completed, your app will exit.
public static void main(String[] args)
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch(InterruptedException e) {}
System.out.println("Thread 2 is finished");
}
});
t.setDaemon(true);
t.start();
System.out.println("Thread 1 is finished");
}
You can use Spring TaskExecutor, it is very useful to raise a thread to run a task.
import org.springframework.core.task.TaskExecutor;
public class TaskExecutorExample {
private class MessagePrinterTask implements Runnable {
private String message;
public MessagePrinterTask(String message) {
this.message = message;
}
public void run() {
System.out.println(message);
}
}
private TaskExecutor taskExecutor;
public TaskExecutorExample(TaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void printMessages() {
for(int i = 0; i < 25; i++) {
taskExecutor.execute(new MessagePrinterTask("Message" + i));
}
}
}
You can check Spring Task Execution documentation here:
http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
Along with you code your Future concept
Future ft=completion.submit(doSomething);
ft.get(timeOut, TimeUnit.MILLISECONDS);
here you can specify Time to execute Thread if it fail to get execute thread get kill(not 100% sure)means it try to interrupt the thread and try to kill
I can resolve my problem as the following code
public static void main(
String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new Runnable() {
#Override
public void run() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
} finally {
System.out.println("Thread 2 is finished");
}
}
});
executor.shutdown();
System.out.println("Thread 1 is 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);
}