Java wait for next print - java

I want the second print to happen after 2 seconds.
System.out.println("First print.");
//I want the code that makes the next System.out.println in 2 seconds.
System.out.println("This one comes after 2 seconds from the println.");

Just use Thread#sleep:
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
Note that Thread.sleep can throw an InterruptedException, so you will need a throws clause or a try-catch, like:
System.out.println("First print.");
try{
Thread.sleep(2000);//2000ms = 2s
}catch(InterruptedException ex){
}
System.out.println("This one comes after 2 seconds from the println.");
or:
public void something() throws InterruptedException {
System.out.println("First print.");
Thread.sleep(2000);//2000ms = 2s
System.out.println("This one comes after 2 seconds from the println.");
}

try {
Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
}

You should use Thread#sleep:
Causes the currently executing thread to sleep
Note that you should use try-catch block around the call to Thread.sleep() because another Thread could interrupt main() while it's sleeping. In this case, it's not necessary to catch it because there is only one Thread active, main().
try {
Thread.sleep(2000)
catch (InterruptedException e) {
System.out.println("main() Thread was interrupted while sleeping.");
}

Thread.currentThread().sleep(2000); //2000 milliseconds = 2 seconds

If you want your java code to sleep for 2 sec you can use the sleep function in Thread:
Thread.sleep(millisec);
The millisec argument is how many milliseconds you want to sleep f.ex:
1 sec = 1000 ms
2 sec = 2000 ms
and so on..
So your code will be something like this:
System.out.println("First print.");
try {
Thread.sleep(2000); //2 secs
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("This one comes after 2 seconds from the println.");
(the try-catch is needed because sometimes it will throw a excpetion if the SecurityManager dont allow the thread to sleep but dont worry, thats will never happen..)
-Max

Related

Facing Issues in Multithreading

I have written a code where it will launch the fixed number of threads from the main class. Below function is just a part of it . All threads will come to this method. I have given thread names like USER1, USER2 etc.
My requirement is that in this method after driver=WebDriver....... statement all of my threads should wait until they all get the driver. I know we can join . But unable to implement here . Can someone please guide
private void testSuitLogin(String driverType){
try{
System.out.println(Thread.currentThread().getName()+" Start Time "+System.currentTimeMillis());
driver = WebDriverFactory.getDriver(driverType);
System.out.println(Thread.currentThread().getName()+" End Time "+System.currentTimeMillis());
homePage();
googleSignIn();
driver.quit();
}
catch(Exception e){
if(driver==null)
{
totalNumberOfUsers--;
return ;
}
}
}
You can use the CountDownLatch. Create a CountDownLatch with a fixed number of thread value and call countdown() after you get the instance of the WebDriver and then call await() to wait until all the threads arrive there.
CountDownLatch countDownLatch = new CountDownLatch(fixedNumber);
private void testSuitLogin(String driverType){
try{
System.out.println(Thread.currentThread().getName()+" Start Time "+System.currentTimeMillis());
driver = WebDriverFactory.getDriver(driverType);
countDownLatch.countDown(); // decreases the value of latch by 1 in each call.
countDownLatch.await(); //It will wait until value of the latch reaches zero.
System.out.println(Thread.currentThread().getName()+" End Time "+System.currentTimeMillis());
homePage();
googleSignIn();
driver.quit();
}
catch(Exception e){
if(driver==null)
{
countDownLatch.countDown();
totalNumberOfUsers--;
return ;
}
}
}
First: If all wait for all to get the driver, then you have a problem when one fails to get the driver.
In order to have all wait for each other (I don't think I have actually ever done that, but here is a suggestion). Since you know the number of threads, you can make something like:
Thread gets driver
Thread calls a synchronized method (only 1 thread can run it at a time) that decrements a counter by 1 (initialized to the number of threads).
Thread yields.
Thread runs again, calls a method that checks if the counter has reached 0.
A: Counter is not 0 yet, thread yields.
B: Counter is 0, thread continues its work.

Producer/Consumer Threads Concurency Java

I have a producer that produces products and a consumer that consumes them. What I want is, if a product is not consumed in 5 minutes I want it to be destroyed.
This is the part of the producer:
boolean full = false;
public void produce(int p) throws RemoteException {
//choses a or b randomly
//if a or b spot is occupied, thread must wait()
synchronized(this){
if ((int)((Math.random()*10)%2) == 1){
while (a!=-1){try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
a = p;
if (b!=-1) full = true;
notifyAll();
}
else {
while (b!=-1){try {
wait();
} catch (InterruptedException ex) {
Logger.getLogger(CHServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
b = p;
if (a!=-1) full = true;
notifyAll();
}
}
}
a & b are supposed to be my products.
I really don't know how can I measure that time for example when the thread is waiting or a client isn't trying to consume that product. This piece of code , is running on a RMI java server.
I'd just using a scheme like this: when you produce something use java.util.Timer() to set a timer for 5 minutes in the future. When the item is consumed, .cancel() the timer. If the timer goes off, do whatever cleanup you need to do.
It looks like you are implementing a queue with 2 slots, the 2 slots being a and b. But the strategy of chosing a random slot isn't optimal. You might wait for a slot while the other is empty. Also, the consumer cannot tell which one of a or b you produced first.
Anyway, if I understand the code well, you could
save the current time at the time you enter the loop.
every time you wake up from wait(), compute the delay since the entry. If it exceeds your time limit, return or throw an exception. Else, check if the slot is available.
to make sure not to wait forever, you should specify a delay on your wait. You could either wait a fixed time, maybe 1 second, or compute the wait time remaining until the 5-minute deadline.

Java Delay/Wait

How do I delay a while loop to 1 second intervals without slowing down the entire code / computer it's running on to the one second delay (just the one little loop).
Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
It seems your loop runs on Main thread and if you do sleep on that thread it will pause the app (since there is only one thread which has been paused), to overcome this you can put this code in new Thread that runs parallely
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
//do stuff
}
My simple ways to delay a loop.
I already put the codes here after failing to follow the stackoverflow's standards.
//1st way: Thread.sleep : Less efficient compared to 2nd
try {
while (true) {//Or any Loops
//Do Something
Thread.sleep(sleeptime);//Sample: Thread.sleep(1000); 1 second sleep
}
} catch (InterruptedException ex) {
//SomeFishCatching
}
//================================== Thread.sleep
//2nd way: Object lock waiting = Most efficient due to Object level Sync.
Object obj = new Object();
try {
synchronized (obj) {
while (true) {//Or any Loops
//Do Something
obj.wait(sleeptime);//Sample obj.wait(1000); 1 second sleep
}
}
} catch (InterruptedException ex) {
//SomeFishCatching
}
//=============================== Object lock waiting
//3rd way: Loop waiting = less efficient but most accurate than the two.
long expectedtime = System.currentTimeMillis();
while (true) {//Or any Loops
while(System.currentTimeMillis() < expectedtime){
//Empty Loop
}
expectedtime += sleeptime;//Sample expectedtime += 1000; 1 second sleep
//Do Something
}
//===================================== Loop waiting
As Jigar has indicated you can use another Thread to do work which can operate, sleep etc independently of other Threads. The java.util.Timer class might help you as well since it can perform periodic tasks for you without you having to get into multithreaded programming.

How to make a thread sleep for specific amount of time in java?

I have a scenario where i want a thread to sleep for specific amount of time.
Code:
public void run(){
try{
//do something
Thread.sleep(3000);
//do something after waking up
}catch(InterruptedException e){
// interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds?
}
}
Now how do i handle the case where the thread i am trying to run is hit with an interrupted exception before the complete of the sleep? Also does the thread wake up after being interrupted and does it go to runnable state or when is it that only after it goes to runnable does the flow go to catch block?
When your thread is hit by an interrupt it will go into the InterruptedException catch block. You can then check how much time the thread has spent sleeping and work out how much more time there is to sleep. Finally, instead of swallowing the exception, it is good practice to restore the interruption status so that code higher up the call stack can deal with it.
public void run(){
//do something
//sleep for 3000ms (approx)
long timeToSleep = 3000;
long start, end, slept;
boolean interrupted;
while(timeToSleep > 0){
start=System.currentTimeMillis();
try{
Thread.sleep(timeToSleep);
break;
}
catch(InterruptedException e){
//work out how much more time to sleep for
end=System.currentTimeMillis();
slept=end-start;
timeToSleep-=slept;
interrupted=true
}
}
if(interrupted){
//restore interruption before exit
Thread.currentThread().interrupt();
}
}
According to this page you'll have to code it to behave the way you want. Using the thread above your sleep will be interrupted and your thread will exit. Ideally, you'd re-throw the exception so that whatever started the thread could take appropriate action.
If you don't want this to happen, you could put the whole thing in a while(true) loop. Now when the interrupt happens the sleep is interrupted, you eat the exception, and loop up to start a new sleep.
If you want to complete the 3 seconds of sleep, you can approximate it by having, say, 10 sleeps of 300 milliseconds, and keeping the loop counter outside a while loop. When you see the interrupt, eat it, set a "I must die" flag, and continue looping until you have slept enough. Then you interrupt the thread in a controlled manner.
Here's one way:
public class ThreadThing implements Runnable {
public void run() {
boolean sawException = false;
for (int i = 0; i < 10; i++) {
try {
//do something
Thread.sleep(300);
//do something after waking up
} catch (InterruptedException e) {
// We lose some up to 300 ms of sleep each time this
// happens... This can be tuned by making more iterations
// of lesser duration. Or adding 150 ms back to a 'sleep
// pool' etc. There are many ways to approximate 3 seconds.
sawException = true;
}
}
if (sawException) Thread.currentThread().interrupt();
}
}
using Sleep in my experience is usually to compensate for bad timing somewhere else in the program, reconsider!
try this:
public void run(){
try{
//do something
long before = System.currentTimeMillis();
Thread.sleep(3000);
//do something after waking up
}catch(InterruptedException e){
long diff = System.currentTimeMillis()-before;
//this is approximation! exception handlers take time too....
if(diff < 3000)
//do something else, maybe go back to sleep.
// interrupted exception hit before the sleep time is completed.so how do i make my thread sleep for exactly 3 seconds?
}
}
if you do not interrupt the sleep yourself, why would this thread be awoken ? is seems that you are doing something very wrong...
I use it this way:
So it is not necessary to wait the specific time to end.
public void run(){
try {
//do something
try{Thread.sleep(3000);}catch(Exception e){}
//do something
}catch(Exception e){}
}
Why do you want to sleep for exactly 3 seconds? If it's just having to execute something after some time, try using a Timer.

How to stop execution after a certain time in Java?

In the code, the variable timer would specify the duration after which to end the while loop, 60 sec for example.
while(timer) {
//run
//terminate after 60 sec
}
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
// run
}
you should try the new Java Executor Services.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
With this you don't need to program the loop the time measuring by yourself.
public class Starter {
public static void main(final String[] args) {
final ExecutorService service = Executors.newSingleThreadExecutor();
try {
final Future<Object> f = service.submit(() -> {
// Do you long running calculation here
Thread.sleep(1337); // Simulate some delay
return "42";
});
System.out.println(f.get(1, TimeUnit.SECONDS));
} catch (final TimeoutException e) {
System.err.println("Calculation took to long");
} catch (final Exception e) {
throw new RuntimeException(e);
} finally {
service.shutdown();
}
}
}
If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:
Thread t = new Thread(myRunnable); // myRunnable does your calculations
long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;
t.start(); // Kick off calculations
while (System.currentTimeMillis() < endTime) {
// Still within time theshold, wait a little longer
try {
Thread.sleep(500L); // Sleep 1/2 second
} catch (InterruptedException e) {
// Someone woke us up during sleep, that's OK
}
}
t.interrupt(); // Tell the thread to stop
t.join(); // Wait for the thread to cleanup and finish
That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.
Your runnable's run would look something like this:
public void run() {
while (true) {
try {
// Long running work
calculateMassOfUniverse();
} catch (InterruptedException e) {
// We were signaled, clean things up
cleanupStuff();
break; // Leave the loop, thread will exit
}
}
Update based on Dmitri's answer
Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.
Depends on what the while loop is doing. If there is a chance that it will block for a long time, use TimerTask to schedule a task to set a stopExecution flag, and also .interrupt() your thread.
With just a time condition in the loop, it could sit there forever waiting for input or a lock (then again, may not be a problem for you).

Categories

Resources