I am implementing a game and I want to ask the player to click on a specific view.
I want my control thread to wait until I get a value back (I have clicked on the view and handled the result). Currently I am doing this by creating a thread, running a method that asks them to click and then entering a while loop that is terminated when the mouse click event changes a variable used in the while loop.
I am writing a game where I have a thread constantly receiving events. On a specific event, I want to prompt the user for a response, but to do this would require me to be on the JavaFX thread (to my knowledge).
Is there a better way of doing this in JavaFX? Thanks!
There are several tools "hidden" in the JDK documentation on threads that can help you resolve this type of issue. Usually when we make a routine code wait for some condition that can proceed we use threads synchronizers.
I want my control thread to wait until I get a value back [...]
CountDownLatch, CyclicBarrier and FutureTask may be classes that can solve your problem. The functionality of these is quite simple. They have the function of stopping threads and release them when some condition is met. The difference in each of these classes is just semantics applied for termination and release threads. Read the documentation of each and see which one is most comfortable to you.
You can also take a look at other sources of study. There is no better source of study in the world (in my opinion) than the content within the book "Java Concurrency In Practice" by Brian Goetz. I assure you that you will become able to easily manipulate threads if you buy this book (or at least gain an incredible knowledge on the subject). Make it clear that you do not need to buy the book to solve your current problem. Buying the book is just my suggestion for you to have more knowledge about threads. You probably will solve your problem by looking at the documentation of classes that synchronize threads I mentioned.
Good luck in your projects. ;)
Related
I'm developing a SWING based Java application with multithreading.
The idea is to create a set of background "tasks/services" to do some tasks repeatedly.
My problem is how to implement multithreading (in the lower level of the application) that can interact with the GUI by displaying SWING components at some conditions.
I know I can use SwingWorker but using that I will turn my application more "gui oriented" wich I don't want to but in the other hand I also don't want to make my multithreading classes depended on GUI classes.
What are the options where?
Thank you in advance.
EDIT
I forgot to mention that this background tasks need to be started in the beginning and cannot be launched by the GUI (like a bootstrap process).
but in the other hand I also don't want to make my multithreading
classes depended on GUI classes.
What about using Observer/ Listener pattern? Your background tasks, launched by SwingWorker, can notify some other components when there is such need. #Xeon comment is pointing you in good direction.
Personal advice: start with some solution and then continuously refactor when code became not so readable.
btw. I hope you remember the old rule: Swing components should be accessed on the Event Dispatch Thread only ;)
You need to learn about concurrency design patterns, such as actors, futures, thread pools ect. Event driven means that you don't have blocking code, eg. rather than me waiting on you and constantly asking if you are finished with your task, you simply tell me once you are ready.
If you go the actor route you can wrap your gui class in a controller which is an actor which will process one message at a time. You need to be carefull with swing that you don't create event loops, as in event A triggers event B which triggers event A again and so on.
That's why an obserever pattern can be nice for displaying data.
But there is no silver bullet for concurrency unfortunately, the actor model is picking up, as well as futures, (take a look at akka), but it is essentially a difficult task so it will always be hard to get right.
Essentially I would say that the easiest approach is to make very strict rules on the sort of concurrency you are willing to accomodate, you need to think about the consequences of adding each bit of parallel functionality, and what effect it has. Then design your code based on that using a well established concurrency model.
What you want to do is the standard way most designers would want to do it, that is, have a background worker class which is independent of the GUI.
Creating a class, MySwingWorker, which extends SwingWorker and which calls your background classes is the standard approach. You may want to create one or more dialog classes to wrap your usage of MySwingWorkers, depending on the complexity of your application.
I'm fairly new to java and I was creating a program which would run indefinitely. Currently, the way I have the program set up is calling a certain method which would perform a task then call another method in the same class, this method would perform a task then call the initial method. This process would repeat indefinitely until I stop the compiler.
My problem is when I try to create a GUI to make my program more user friendly, once I press the initial start button this infinite loop will not allow me to perform any other actions -- including stopping the program.
There has to be another way to do this?
I apologize if this method is extremely sloppy, I sort of taught myself java from videos and looking at other programs and don't entirely understand it yet.
You'll need to run your task in a new thread, and have your GUI stuff in another thread.
Actually, if you keep working on this problem, you'll eventually invent event driven programming. Lots of GUI based software, like Android, use this paradigm.
There are several solutions. The first that comes to mind is that you could put whatever method needs to run forever in its own thread, and have a different thread listen for user input. This might introduce difficulties in getting the threads to interact with each other, but it would allow you to do this.
Alternatively, add a method that checks for user input and handles it inside the infinite loop of your program. something like below
while(true){
//do stuff
checkForUserInput();
//do other stuff
}
To solve this problem, you need to run your UI in another thread.
Many programs are based on an infinite loop (servers that keep waiting for a new user to connect for example) and your problem isn't there.
Managing the CPU time (or the core) allocated to your infinite loop and the one allocated to take care of your UI interactions is the job of the operating system, not yours : that's why your UI should run in a separate thread than your actual code.
Depending on the GUI library (Swing, ...) you're using there may be different ways to do it and the way to implement it is well answered on Stack Overflow
I came across Java: notify() vs. notifyAll() all over again but still could not satisy myself.
xagyg explained it very well but in the end it became very complex to memorize the concept.
I am trying my best here with simple daily life example so that i and others can come back to this if any one forget. My source of understanding
is answer by xagyg in above link but trying to simplyfy the things here.
Say two guys go to movie theatre and found its houseful. But then box office guy say Jon told them there is a ticket that has been
reserved for president. If he does not come, he will sell it off. Then guys told to jon, ok we are waiting in hotel near by, please
notify us when you get any info. These guys go to hotel and sleep. Now president does not turn up, now Jon has two options
First is notify one of the guy and let other sleep. If he does that one can go movie while other will probably continue to sleep(till
he doesn't get notified. I am assuming this guy didn't have sleep for a year :)). Another option is he notifies(awakens) both of them,
choose any one of them(In actual java example program does not select but its vm/thread scheduler) for movie.In that case he will keep other guy in hotel room as he can create some kind of issues :(. Now once
the show ends, this guy can go for next show if ticket is available. Consider ticket as lock, theatre as object. This what exactly
notify and notifyAll does. So it is clear that notifAll is better over notify when in confusion
Now consider producer/consumer example.
say two consumer thread are waiting for production in store. Now what producer does, he produces two items in single go and exit. Now if producer use notify, only one thread can consumer while other will continue to wait for forever.
But if producer uses notifyAll() here, both thread can go for consumption one at a time
Let me know if my understanding is correct?
I don't think what you've written in the last statement is correct. Each time the producer produces an object it is supposed to notify a consumer, so if 2 objects are created it should invoke notify twice and not just once. This way if you use notify instead of notifyAll, you will still be able to get both consumer threads to consume
I have a GUI and the GUI is starting another thread (Java). This thread is starting a class which is crawling many websites. Now I want to show in the GUI how many websites are crawled and how many are left.
I wonder what's the best solution for that.
First idea was to start a timer in the GUI and periodically ask the crawler how many is left. But I guess this is quite dirty...
Then one could pass the GUI to the crawler and it is calling a GUI method every time the count of ready websites changes. But I don't think that's much better?
What is the best way to do something like that?
It depends.
Ask the crawler how much work it is done isn't a bad idea. The benefit is you can actually control when an update occurs and can balance out the load.
The downside is that the information may go stale very quickly and you may never get accurate results, as by the time you've read the values, the crawler may have already changed them.
You could have the crawler provide a call back interface, which the GUI registers to and when the crawler updates it's states, calls back to the GUI.
The problem here is the UI may become swamped with results, causing to lag as it tries to keep up. Equally, while the crawler is firing these notifications, it isn't doing it's work...
(Assuming Swing)
In either case, you need to make sure that any ideas you make to the UI are made from within the Event Dispatching Thread. This means if you use the callback method, the updates coming back will come from the crawlers thread context. You will need to resync these with the EDT.
In this case you could simply use a SwingWorker which provides mechanisms for syncing updates back to the EDT for you.
Check out Concurrency in Swing for more details
register a callback function to your thread. when your data is dirty, invoke this callback function to notify GUI thread to update. don't forget to use synchronization.
I can't seem to find any documentation on the details of an Activity's run loop for Android.
Apple documents the "anatomy of a run loop", and that's pretty much what I'm looking for. The Android documentation just says "Activity Is Running" in its life cycle state diagram. Obviously that's backed up by some sort of run loop.
Anyone have some insight (aka Documentation) into the internals of an Activity's run loop?
edit - I should clarify that I presume the run loop is actually owned and run by the main UI thread. The current Activity's functionality is likely injected into this runloop at a certain point. I'm interested in the overall UI thread run loop, as well as what role the Activity takes in it.
The short answer is, "don't worry about it, it's done for you."
Activities and other constructs sit on top of android.os.Looper, communicating with it through instances of android.os.Handler. A Looper manages your "run loop," dispatching messages from a queue and blocking the thread when it's empty. Handlers communicate with a thread's Looper and provide a mechanism for working with the message queue.
Most of the time you won't need to work with either one directly. Lifecycle events for your major application components like Activities and Services will be dispatched to your code. If you're curious as to what's under the hood, sources for both are available:
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Looper.java
https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/Handler.java
Updated:
There's really nothing specific being referred to by "Activity is running." The Activity is simply displaying its UI, handling input, executing any necessary functions, and starting another Activity.
If you're interested in what implications multi-threading would have on the run-loop, there isn't really a concrete relationship. Your threads can just do their work, and the Activity's state will function independently and automatically update its UI (provided you call postInvalidate() correctly).
Original:
Take a look at the first diagram on this page: http://developer.android.com/reference/android/app/Activity.html
It specifies the "lifetime" of each Activity and what states it can be in, if that's what you're looking for.