I am working on a console game in Java that has 10 rounds that are 2 minutes each. I need a way to use threads to alert the user every 30 seconds that have passed and then override the main method and break the user out of the game loop after two minutes have passed.
How could I use threads to break the main loop out of one function and return the user to another one?
Thanks
You can either use non blocking API (that give you for example the current state of the keyboard/mouse rather than block) in a loop and just not run the next iteration when the time out occured.
Or you can interrupt the thread if this one is blocked/sleeping on a blocking API calling this the interupt method of that thread:
refToThreadToInterupt.interupt();
This will generate an InteruptedException if the thread is blocked or set the interupt flag to true otherwise. Can be checked by the thread with:
refToThreadToInterup.isInterupted();
As you have no idea as of what the thread is doing when you interupt it, you don't know if you get the exception or if the boolean will just be set to true, so you have to deal with both cases.
Related
My question considers, as an example, the scenario where the thread T is put to sleep for X time, and then T gets an interrupt call from another thread, which will make it raise an InterruptedException at some point. I'm mainly concerned with the performance impact of the implementation choice for this, and why is it low or high. From my understating of how things work on a low level, a java sleep() call calls inside of it the sleep function of the OS, which instructs the scheduler to keep the thread in a non executing state and check every Y time for each thread if the sleep time has elapsed (this check is triggered by a signal separate from the cpu clock that is thrown once every many clock cycles, as to not have too much impact on performance).
Is this correct?
I'm guessing that one solution might be that the sleep(x) method in java has an internal cycle that repeatedly checks for the interrupted flag. If this didn't call the sleep function of the OS, the thread would keep getting scheduled just repeating that check and consuming a lot of cpu time(as much as a thread that is not sleeping and working without interruptions). Does the java sleep(x) method actually call the OS sleep(t) more than once, with t being a fraction of x, so that the thread performs the check on the interrupted flag once in a while? This would still mean that every thread that is sleeping gets woken and put to sleep again multiple times, is this optimal?
If question 2 is false, what does actually happen?
Edit: I'm assuming a scenario where the OS has threads implemented and the JVM uses them, if this changes the possible answer to this question.
In the below code:
class Test {
public static void main(String [] args) {
printAll(args);
}
public static void printAll(String[] lines) {
for(int i=0;i<lines.length;i++){
System.out.println(lines[i]);
Thread.currentThread().sleep(1000);
}
}
}
Will each String in the array lines output:
With exactly 1-second pause between lines?
With at least 1-second pause between lines?
Approximately 1-second pause. The thread can be woken up beforehand and you'll get an InterruptedException, or the thread can sleep for 1000ms and then not get to run immediately, so it will be 1000ms + microseconds (or more, if there are higher priority threads hogging the CPU).
You're also calling it wrong. It's Thread.sleep(1000);, as a static method it always acts on the current thread and you can't make other threads sleep with it.
So it will sleep for exactly 1 second to the best of it's knowledge. The thread.sleep method is not perfect. See this and other related questions:
https://stackoverflow.com/a/18737109/4615177
Calling Thread.sleep(1000) method, put the current executing thread in waiting state for the specified time. As per your program, it seems only a single threaded program hence,while The calling thread is in waiting state, no other thread is in running state, so after 1000 ms your thread will get chance to execute almost after 1000ms but not sure for other application where no of threads are going to execute.
Some points about Thread.sleep
1. it is always the current thread that is put to sleep
2. the thread might not sleep for the required time (or even at all);
the sleep duration will be subject to some system-specific granularity, typically 1ms;
3. while sleeping, the thread still owns synchronization locks it has acquired;
4. the sleep can be interrupted (sometimes useful for implementing a cancellation function);
5. calling sleep() with certain values can have some subtle, global effects on the OS
So at the end you can each String output will be with at least 1-second pause between lines.
And you calling it wrong. It is a static method..:)
It'll sleep for at least 1 second if not interrupted by some other thread. If some other thread interrupts it, InterruptedException will be thrown.
Ideally, it'll sleep for 1 second, once that time has elapsed, it will wait for it's turn to get into running state again.
Read the documentation. (Why did no one else say that?) The javadoc for Thread.sleep() says,
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
That's pretty vague, but that's all the guarantee you will get. The exact behavior will depend on what operating system you are running and probably on what JVM you are running.
An application that requires precise timing is called a real-time application, and there are special real-time operating systems (RTOS) that will tell you within how many microseconds of its scheduled time an event actually will occur. you can even get real-time versions of Java to run on your RTOS. http://en.wikipedia.org/wiki/Real_time_Java
I was wondering if anyone had information regarding how to set a flag to indicate when all the threads are done running?
I have 7 threads that run concurrently but I need to set a flag to show when all of them are finished to run a method to update the database table so it can switch to the other service. This is the first time I am using threads so if anyone could point me in the right direction that would be great.
You can try with CountDownLatch. It will full fill your requirement, What you have to do is, create an instance of CountDownLatch with count value equal to the number of threads. Start all the thread and call await method in main thread. Have the CountDownLatch object reference in all the threads and call the countDown method in each thread after completing its own job. For each countDown method, the CountDownLatch count value will get decrement. Once it reaches to zero the method where await is called will get wake-up. Note if any one of your thread fails to call countDown then await will never get wake-up.
Try this for your reference,
http://www.java-redefined.com/p/java-count.html
Use the join method to wait for each thread to finish execution.
for (Thread t : threads) {
t.join();
}
If you're using threads directly, check out CountDownLatch. Depending on how complex your workflow is, you may prefer the Phaser.
I have a simple java application which calculates prime numbers up to a certain user-given number and prints out the numbers. I've built upon this to include four separate threads which iterate through 4 separate ranges of numbers. Once all 4 threads have completed their iterations I want to print the final ArrayList.
I'm currently getting a ConcurrentModificationException because after I start the 4 threads, the next line of code is the print statement which is trying to print the ArrayList which is at that moment being modified by at least one of the still active threads.
Therefore, I want to be able to have the print statement execute after all 4 threads have died. Furthermore, I would like to do this without using a spinning loop. I have nothing in particular against using a spinning loop except that I imagine there is a better way to do this and I would probably have to assign greater priorities to the 4 threads in order to prevent the spinning loop from using up a significant amount of the CPU.
Use a CountDownLatch initialized to 4; the print thread awaits the latch, and the worker threads call countdown on the latch before they terminate.
Be sure to properly synchronize your ArrayList as well if four threads are modifying it at once; you may want to use a ConcurrentLinkedQueue instead (or else use a different ArrayList for each thread)
Use a CountdownLatch. The Javadoc for that class tells how to have
The main thread creates the latch with the number of threads.
The main thread starts all the working threads.
Each thread has a reference to the latch.
It counts the latch down when it finishes its work.
The main thread waits for the latch to count down to 0.
The main thread does the printing job.
If you use a java.util.concurrent.BlockingQueue, each thread could put() an item on the blocking queue when it is finished.
Before the print statement, the code could do a take() from the blocking queue and only proceed when the take() has returned once for each thread. The printing thread will block on the take() while there is nothing there for it to take. That will guarantee that the printing doesn't commence until all the threads have finished.
I have a state machine, which is used by many threads to manage the states of a game. I need to be able to clean the threads if something happens and an instance of a game does not change state for whatever reason.
How could i do this, i have the state machine?
If I'm getting you properly you mean to terminate threads given an event and check out if a state doesn't change. You could do it in a number of ways. Let me suggest you a possible solution.
1 - A simple way to terminate your threads would be to put those threads in a list, array, etc. a way to identify what threads you want to terminate.
2 - Create a method that terminateTheadList(...).
3 - To terminate them a way to do it would be to use the java.lang.Thread .interrupt() method. Iterate over your Thread list, array,etc. and interrupt() them. Then once you get the exception allow the thread to terminate.(that is to say, do not catch this exception and loop).
4 - To check you if the instance of the game create a new thread (this one should not be in your thread terminate list) that checks out that instance game and puts the last time this changed. Sleeps and checks out again. if the instance haven't changed call your terminateThreadList method again.
I hope this helps