I'd always worked in java with the understanding that if I farmed off a task to the event thread, it could use any suitiable locks it needed and it would never bump into with any other locks I made from the event thread.
Unfortunately, my webstart program has three event threads, and two of them are deadlocking.
I have AWT-EventQueue-0 in the main thread-group
This hangs inside a paint operation, trying to perform a getRowColor() operation to prepare a renderer for a table cell. As it's painting, it has the component tree-lock.
I have AWT-EventQueue-1 of the javawsSecurityThreadGroup which seems harmless enough, it looks like it might be uninvilved in the hangs, but it does get hung up on an invalidate() call for a text component (Java console?)
Lastly, I have AWT-EventQueue-2, of the javawsApplicationThreadGroup.
This particular component obtains a write-lock for purpose of setting the table data (which blocks reads against row color). This then stalls on an update of the focused cell, which flows down scrollRectToVisible(), validateView(), updateCursor(), findComponentAt(), which needs the tree-lock held by the paint operation underway on AWT-EventQueue-0
The read-lock/write-lock is our code, and exists to let programmers worry less about threading. I'm not prepared to axe it just because the application decides it needs extra event threads to run in parallel.
Ultimately, I want our application using a single AWT-EventThread. Is there a way to get one of the event thread to farm requests off to the other? Or to select which event thread is used for painting, or used when an invokeLater()/invokeAndWait() happens?
I'm not sure if it matters, but we do make use of FX in our application.
Try reducing the scope of the critical sections guarded by your write locks to only writing to memory.
If you push from the critical section the subsequent notifications to update the UI, which depend on the write but are not part of the critical section for the write, and allow them to use the read lock via other control paths, your deadlock issues should resolve.
Another option may be to fork your write tasks to background threads (maintaining proper synchronization; see also java.util.concurrent.ExecutorService) and then send notifications when writes are complete that can be executed asynchronously in the display thread.
I don't have this figured out to a fair-thee-well yet, but I think I've got enough for anyone to chase it back to a final solution. I'll note, evidently my environment is in some way unique to Macintosh computers, as I'm not the first person looking at this problem on a Macintosh system, and I've never before encountered this problem under a Windows setting.
Java-Webstart kicks things off. It invokes the application main() method with a thread in the Thread Group titled javawsApplicationThreadGroup. This puts the thread in an appropriate application context, which causes any AWT/Swing calls to be passed off to the AWT-EventQueue-2, which is in this thread group.
This includes not only invokeLater(), but repaint() calls as well.
We also start up JavaFX from this thread. For whatever reason, it puts the JavaFX Application Thread in the "system" threadgroup. The system threadgroup is a bit tricky, the dev tools I use (Eclipse IDE/JProfiler) don't normally show threads in this group, making it a poor choice for anything. We will also hand off requests from FX to Swing from here using InvokeLater(), and I'm sure no shortage of repaint()s. I've not verified this directly, but quick emperical tests suggests requests from the FX Application Thread under the "system" go to the AWT-EventQueue for the "main" threadgroup.
This at least explains what I'm looking at and gives me the tools I need to combat the problem.
First steps to resolving this: Top of the main method, I locate the "main" threadgroup and kick off a new thread in that group to perform the actual application startup. This causes both the FX Application Thread to spawn under the main thread group, as well as our main thread-pool. Result, both FX and background tasks submit swing requests to the same event queue. This doesn't quite fix everything for me (still have some business logic running from threads in the javawsApplication thread group), but I think it gives me all the tools I need to reach a solution.
public static void main(String[] args)
{
startFromMainThreadGroup(args);
}
private static void startFromMainThreadGroup(final String[] args)
{
ThreadGroup tgSystem = Thread.currentThread( ).getThreadGroup( );
ThreadGroup ptg;
while ( (ptg = tgSystem.getParent( )) != null )
{
tgSystem = ptg;
}
ThreadGroup tgMain = null;
ThreadGroup[] groups = new ThreadGroup[tgSystem.activeGroupCount() + 16];
int numGroups = tgSystem.enumerate(groups);
for(int i = 0; i < numGroups; i++)
{
if("main".equals(groups[i].getName()))
{
tgMain = groups[i];
break;
}
}
if(tgMain == null)
{
tgMain = tgSystem; // Fallback
}
Runnable doRun = new Runnable()
{
#Override
public void run()
{
mainImpl(args);
}
};
Thread thread = new Thread(tgMain, doRun, "mainFork");
thread.setDaemon(false); // Explicit
thread.start();
}
Related
I am fairly new to java, and am starting to get into using different threads in order to use wait() or sleep() on one part of my code and have the others still run.
For this project, I am using JFrame with the javax.swing.* and java.awt.* imports. What I am trying to do is have one of the threads (in my code it is the main, starting thread) allow the player to choose a space on the tic tac toe board, and when they click it, it will change icons, and then the AI will wait for 1 second before playing back from the second thread that I created.
Unfortunately, whenever I call ait.sleep(1000) (ait is my thread name) both threads wait for 1 second before finishing their execution. Can anyone tell me why sleeping one thread is stopping my whole execution?
Can anyone tell me why sleeping one thread is stopping my whole
execution
to better explain your Swing GUI is created on its own special thread separate from that which main() and other code will run in, this is done via creating your Swing components in the SwingUtilities.invokeXXX block (even if you have not done this your GUI will be run on a single thread called the initial thread) . Now if you simply call sleep while on Event Dispatch Thread (or for that matter on the same Thread) it will wait for the call to Thread.sleep to finish. Now because all Swing events are processed on EDT we pause its execution by calling sleep(..) thus pausing the UI events from being processed and therefore GUI is frozen (until sleep(..) returns).
You should not use Thread.sleep(..) on Event Dispatch Thread (or any Thread where sleep will cuase unwanted execution blocking), as this will cause the UI to seem frozen.
Here is a nice example which demonstrates exactly, this unwanted behavior caused by invoking Thread.sleep(..) on GUI's EDT.
Rather use:
Swing Timer for example:
int delay=1000;// wait for second
Timer timer = new Timer(delay, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
//action that you want performed
}
});
//timer.setRepeats(false);//the timer should only go off once
timer.start();
Swing Worker
or if no Swing components are being created/modified:
TimerTask
Thread, you would then use Thread.sleep(int milis) (but thats last option in any case IMO)
UPDATE
Swing Timer/SwingWorker was only added in Java 1.6, however, TimerTask and Thread have been around for alot longer sine Java 1.3 and JDK 1 repsectively, thus you could even use either of the 2 above methods and wrap calls that create/manipulate Swing components in SwingUtilities/EventQueue#invokeXX block; thats the way things used to be done :P
Thread.sleep is a static method. Invocations of it via the reference of any given Thread is simply a form of convenience.
As a result, any invocation of sleep is really calling sleep on the current Thread, which I suspect is the Event Thread in your case. Sleeping/blocking on the Event Thread will give the appearance of being locked up.
If you want the ait thread to sleep, then code that thread to sleep. Designs where one thread "reaches into" another and pushes it around at a low level are fundamentally broken. You write the code for every thread, so write it to do what you want it to do in the first place so you'll find no need to reach into it from the outside.
Which makes more sense, for the person in the kitchen to know how to cook breakfast or the person in the bedroom to yell down and direct them to perform each step of making breakfast? Sure, you might tell them to make breakfast. But you definitely don't direct each step at a low level.
Thread.sleep is a static method which causes the currently executing thread to sleep for the specified amount of time. Java syntax allows you to call a static method via a variable, but the compiler simply uses the compile-time type of that variable to determine which method to call, i.e.
Thread ait = null;
ait.sleep(1000); // calls Thread.sleep(1000), causing current thread to sleep.
// In particular, does *not* NPE
You also mentioned wait() - while this is an instance method rather than a static it still causes the current thread to do the waiting (ait.wait(1000) would cause the current thread to wait for up to 1 second or until another thread calls ait.notifyAll()).
There is a Thread.suspend() and its counterpart resume() that were introduced in the very early days of Java to allow one thread to control another, but they were deprecated soon after as they are inherently deadlock-prone. The recommended pattern if you want one thread to "control" another is to do it co-operatively, i.e. have some kind of shared flag that thread A sets and thread B reads, and have B send itself to sleep according to the flag:
volatile boolean threadBShouldRun = true;
// Thread B
while(true) {
if(threadBShouldRun) {
// do some stuff
} else {
Thread.sleep(1000);
}
}
// Thread A
if(someCondition) {
threadBShouldRun = false;
}
but it's generally easier and less error-prone to make use of the facilities that exist in the java.util.concurrent package. Doing multi-threading right is much harder than it appears on the surface.
I am trying to write a multi-thread program with Swing. Essentially how the program works is that when it runs it will have a robot(represented by a circle in screenshot) that is wondering around in a field. This robot should be controlled by a thread of it's own. The program has a button "Launch Robot" that will create another robot on the field(upto a max of say 10). Right now I have the basics of the program, but it all runs under one thread. I can launch as many robots as I want but they all run under a single thread. But I want that whenever I click "launch Robot" an independent thread be created and control that robot. This is how the program looks right now:
The UML diagram for the program is as following:
Since its a bit long I won't post the whole program. But the method that starts and updates the robots(currently controlling only one robot on the field) is as follows:
public void gameStart(){
Thread gameThread = new Thread(){
public void run(){
while(true){
//execute one time step for the game
gameUpdate();
//refresh screen
repaint();
//give other threads time
try{
Thread.sleep(1000/UPDATE_RATE);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
};
gameThread.start();
}
My question is how can I achieve multi-threading for such a scenario? I know the basics of SwingWorker, but since I haven't done any multi-threading, I have no idea on how to make several threads work and be updated by one thread(update position of robots that are controlled by threads).
EDIT: Just to make my point, this is a project that I am working on. It's not about if multi-threading makes sense in this scenario or not.
Create a RobotModel that contains a Collection<Robot> and defines their interaction. Iterate the model in the doInBackground() implementation of a SwingWorker. Invoke publish() as meaningful events arise, and process() updates to the RobotWorld view by querying the model. As discussed here, there should be no drawing in the model and no interaction logic in the view. A single worker should suffice for a moderately complex model, but you can synchronize multiple workers as shown here.
A good option to achieve this is to use ScheduledThreadPoolExecutor.
Instantiate the thread pool via:
ScheduledThreadPoolExecutor threadsPool = new ScheduledThreadPoolExecutor(size);
To create a new Robot Thread, use:
threadsPool.submit(new Runnable() {
#Override
public void run() {
launchRobot();
}
});
This way, each invocation will instantiate a new Thread.
You can set the limit of the total number of allowed Thread via the "size" argument.
You can also pass a result after each thread completes using:
public <T> Future<T> submit(Runnable task, T result)
If you want less detail, you could let Java do the work for you with the following convenience API:
Executors.newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation) or:
Executors.newFixedThreadPool(int) (fixed size thread pool)
Remember us, Executor. Remember what was done here today. And may Adun watch over you
This robot should be controlled by a thread of it's own.
Why?
IMO, the most important way to describe any thread is to say what it waits for. In an internet server, an accept thread waits for incoming connections from new clients, and a client thread waits for additional commands from a single client. In a program that performs massive parallel computations, a worker thread waits for tasks to be performed. In a GUI program, the event dispatch thread waits for keyboard and mouse events. Etc., etc.
What will your robot thread wait for?
If it waits for time to pass (i.e., if it calls Thread.sleep()), then your GUI framework probably already has a timer thread that does that, and you might want to consider using it. (In Swing, you would use the javax.swing.Timer class to submit new timed tasks.)
I have a javaFX application which visualizes compuational geometry algorithms. The execution of an algorithm happens in another thread, lets call it mainComputingThread.
An algorithm can update the UI at any time by adding/removing/modifying shapes.
so the code will look like:
//do some computaions (1)
updateUI();
//do some more calculations (2)
What I want know is in the updateUI method to update the UI immediately and prevent the calling thread from running further (marked as (2)) until the UI update is done.
I thought about boolean guards. So the code could would look like:
updateUI(){
boolean guard = false;
Platform.runLater(new Runnable()
{
run(){
//do the actual update
guard = true;
}
});
while(guard==false);
}
I hope you get an idea of what I mean. I'm really curious if there's a better solution for this problem...
Simple approach: block background thread until update is complete:
You need to update the UI on the FX Application Thread. Typically you do this by passing a plain Runnable to Platform.runLater(...).
If you want to wait for that ui update to complete before proceeding, instead create a FutureTask and pass it to Platform.runLater(...). Then you can call get() on the FutureTask, which will block until the task is complete:
private void updateUI() throws InterruptedException {
// actual work to update UI:
FutureTask<Void> updateUITask = new FutureTask(() -> {
// code to update UI...
}, /* return value from task: */ null);
// submit for execution on FX Application Thread:
Platform.runLater(updateUITask);
// block until work complete:
updateUITask.get();
}
This lets the FutureTask handle all the tricky work of waiting and notifying: it is always better to use a higher-level API for this kind of work when you can.
If you like, you can refactor this into a utility method, similarly to Dainesch's answer:
public class FXUtils {
public static void runAndWait(Runnable run) throws InterruptedException {
FutureTask<Void> task = new FutureTask<>(run, null);
Platform.runLater(task);
task.get();
}
}
Alternative approach: ensure that no more than one update is consumed during any frame rendering, blocking the background thread if an update is pending
Here is a somewhat different approach. Create a BlockingQueue with a capacity of 1 to hold the Runnables that update the UI. From your background thread, submit the Runnables to the blocking queue: since the blocking queue can hold at most one element, this will block if one is already pending.
To actually execute the updates in the queue (and remove them, so more can be added), use an AnimationTimer. This looks like:
private final BlockingQueue<Runnable> updateQueue = new ArrayBlockingQueue<>(1);
background thread code:
// do some computations...
// this will block while there are other updates pending:
updateQueue.put(() -> {
// code to update UI
// note this does not need to be explicitly executed on the FX application
// thread (no Platform.runLater()). The animation timer will take care of that
});
// do some more computations
Create the timer to consume the updates:
AnimationTimer updateTimer = new AnimationTimer() {
#Override
public void handle(long timestamp) {
Runnable update = updateQueue.poll();
if (update != null) {
// note we are already on the FX Application Thread:
update.run();
}
}
};
updateTimer.start();
This basically ensures that no more than one update is ever scheduled at any time, with the background thread blocking until any pending updates are consumed. The animation timer checks (without blocking) for pending updates on each frame rendering, ensuring that every update is executed. The nice thing about this approach is that you can increase the size of the blocking queue, effectively keeping a buffer of pending updates, while still ensuring no more than one update is consumed during any single frame rendering. This might be useful if there are occasional computations that take longer than others; it gives these computations a chance to be calculated while others are waiting to be executed.
Hard question to answer without having the reason why you want to stop processing before the UI update is done. (Note: the runLater method executes the UI updates in the order received) Is it to prevent spamming to many Runnables to the JavaFX thread? Other reasons?
Your basic idea however works with the use of a CountDownLatch so that the processing thread waits to acquire a permit. If you choose that approach use something like this:
public class MyFXUtils {
public static runAndWait(final Runnable run) {
final CountDownLatch doneLatch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
public void run() {
try {
run.run();
} finally {
doneLatch.countDown();
}
}
});
doneLatch.await();
}
}
EDIT: replaced Semaphore by CountDownLatch
EDIT:
So, the quickest way I always do it in prototypes is as following, transform:
//do some computaions (1)
updateUI();
//do some more calculations (2)
into
ExecutorService executor = Executors.newFixedThreadPool(1);
class JobStep implements Runnable {
public void run() {
doSomeComputations();
Platform.runLater(() -> {
updateUI();
executor.submit(new JobStep());
});
}
executor.submit(new JobStep());
OLD PART
Not an answer, but a suggestion how to attack the problem.
From my experience, the complete solution would be much more elaborate. I would separate the JavaFX shape instances from the shapes, which your algorithm does process. I would do it by means of using different class types and synchronize between the two.
The graphical algorithms have the tendency to be a lot quicker than the ones that are visualizing it. If the algorithm runs on small data set, then the rendering most often tend to slow down it significantly. It can easily be seen by running the same algorithm with and without visualization.
If the data set is bigger than the most trivial ones, then drawing of a single frame can easily take more than one second. Interactive visualizations are expected to respond in "real time", preferably many times per second.
The data visualization facilities have many means to tackle the problem. The best candidates always include:
Simplifying visualization. Drawing simpler shapes instead of complex, like removing the rounding from boxes. The LOD (level of detail) also applies to this point: during interactive scroll the visualized elements might be replaced by bounding box counterparts.
Selective hiding. Drawing only a part of the whole data set.
Parallelizing and hardware acceleration. The GPU's natively provide many means to handle complex visualizations. Typically the low level programming APIs (OpenGL, shader programs) allow much better throughput than every high level wrapping API, including JavaFX
Most often, the end solutions incorporate not only above points, but also others, including domain specific optimizations.
The visualization facilities always come with a lot of restrictions, like the most common one: have to be updated in the dedicated thread (thread confinement approach). They also come with visualization specific data structures.
From the data processing algorithm stage, one of the most common requirements is that it cannot be blocked or delayed by visualization. The algorithms are also written in a style, which doesn't translate to well for the means of visualization: imperative loops over data structures instead of updating observable drawable objects. There is a good reason to it though: the algorithms are expected to be optimized for performance or memory consumption.
One architectural approach to the problem might be as following:
The data processing stage produces snapshots at predefined points. The adding, modifying and remove operations are all published as this packet. It can be a just a copy of data structure that is being processed or it can be in the form of the coalesced events.
The data processing and data visualization run on different threads. They communicate only by means of publishing snapshots, never by blocking each other directly.
The snapshots shouldn't be restricted to particular frame rate. There should be means to batch updates before drawing or drawing same batch multiple times if the data processing stage stalls.
I strongly recommend reactive approach to the problem. The RxJava provides nice example for the "suggestion box" feature. It's very good at correctly handling requirements like "Every key update do a long running process on different thread and discard the last one, if any was running. Or maybe, don't do it on every key update, but wait 50ms for the user to make up his mind before he ends typing".
I am fairly new to java, and am starting to get into using different threads in order to use wait() or sleep() on one part of my code and have the others still run.
For this project, I am using JFrame with the javax.swing.* and java.awt.* imports. What I am trying to do is have one of the threads (in my code it is the main, starting thread) allow the player to choose a space on the tic tac toe board, and when they click it, it will change icons, and then the AI will wait for 1 second before playing back from the second thread that I created.
Unfortunately, whenever I call ait.sleep(1000) (ait is my thread name) both threads wait for 1 second before finishing their execution. Can anyone tell me why sleeping one thread is stopping my whole execution?
Can anyone tell me why sleeping one thread is stopping my whole
execution
to better explain your Swing GUI is created on its own special thread separate from that which main() and other code will run in, this is done via creating your Swing components in the SwingUtilities.invokeXXX block (even if you have not done this your GUI will be run on a single thread called the initial thread) . Now if you simply call sleep while on Event Dispatch Thread (or for that matter on the same Thread) it will wait for the call to Thread.sleep to finish. Now because all Swing events are processed on EDT we pause its execution by calling sleep(..) thus pausing the UI events from being processed and therefore GUI is frozen (until sleep(..) returns).
You should not use Thread.sleep(..) on Event Dispatch Thread (or any Thread where sleep will cuase unwanted execution blocking), as this will cause the UI to seem frozen.
Here is a nice example which demonstrates exactly, this unwanted behavior caused by invoking Thread.sleep(..) on GUI's EDT.
Rather use:
Swing Timer for example:
int delay=1000;// wait for second
Timer timer = new Timer(delay, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
//action that you want performed
}
});
//timer.setRepeats(false);//the timer should only go off once
timer.start();
Swing Worker
or if no Swing components are being created/modified:
TimerTask
Thread, you would then use Thread.sleep(int milis) (but thats last option in any case IMO)
UPDATE
Swing Timer/SwingWorker was only added in Java 1.6, however, TimerTask and Thread have been around for alot longer sine Java 1.3 and JDK 1 repsectively, thus you could even use either of the 2 above methods and wrap calls that create/manipulate Swing components in SwingUtilities/EventQueue#invokeXX block; thats the way things used to be done :P
Thread.sleep is a static method. Invocations of it via the reference of any given Thread is simply a form of convenience.
As a result, any invocation of sleep is really calling sleep on the current Thread, which I suspect is the Event Thread in your case. Sleeping/blocking on the Event Thread will give the appearance of being locked up.
If you want the ait thread to sleep, then code that thread to sleep. Designs where one thread "reaches into" another and pushes it around at a low level are fundamentally broken. You write the code for every thread, so write it to do what you want it to do in the first place so you'll find no need to reach into it from the outside.
Which makes more sense, for the person in the kitchen to know how to cook breakfast or the person in the bedroom to yell down and direct them to perform each step of making breakfast? Sure, you might tell them to make breakfast. But you definitely don't direct each step at a low level.
Thread.sleep is a static method which causes the currently executing thread to sleep for the specified amount of time. Java syntax allows you to call a static method via a variable, but the compiler simply uses the compile-time type of that variable to determine which method to call, i.e.
Thread ait = null;
ait.sleep(1000); // calls Thread.sleep(1000), causing current thread to sleep.
// In particular, does *not* NPE
You also mentioned wait() - while this is an instance method rather than a static it still causes the current thread to do the waiting (ait.wait(1000) would cause the current thread to wait for up to 1 second or until another thread calls ait.notifyAll()).
There is a Thread.suspend() and its counterpart resume() that were introduced in the very early days of Java to allow one thread to control another, but they were deprecated soon after as they are inherently deadlock-prone. The recommended pattern if you want one thread to "control" another is to do it co-operatively, i.e. have some kind of shared flag that thread A sets and thread B reads, and have B send itself to sleep according to the flag:
volatile boolean threadBShouldRun = true;
// Thread B
while(true) {
if(threadBShouldRun) {
// do some stuff
} else {
Thread.sleep(1000);
}
}
// Thread A
if(someCondition) {
threadBShouldRun = false;
}
but it's generally easier and less error-prone to make use of the facilities that exist in the java.util.concurrent package. Doing multi-threading right is much harder than it appears on the surface.
I've been trying to teach myself concurrency, and I've run into an issue. I understand that two Java threads can communicate to each other via wait() and notify(). However, this requires one thread to be inactive and essentially "just sitting around" until the other one wakes it up.
Is it possible to have both threads running simultaneously and still have them listening for notifications from the other? Would this be accomplished through concurrency techniques or instead something like an ActionListener?
For example, the project I'm testing this on is basically a grid where different entities wander around through different cells. When two of the entities happen to wander into the same cell, I'd like one to notify the other and something different to happen based on this (for instance, a greeting: "Hello there!"). But as it stands, with the wait/notify paradigm, one of the threads/entities has to simply sit in one cell waiting for another to wander in; they can't both move around.
There's a few ways you can communicate between threads. Using the most common approach you can use instance variables to share info between threads but you must take care to only write from one thread or synchronize any updates to the shared variable. Alternatively you can use Piped I/O streams which were designed for inter-thread communication, or passing raw data between threads. One thread writes info to the stream while the other reads it.
Here's an example method that would read output from a slow network connection and dump it to System.out using threads.
public void threads() throws IOException {
final PipedOutputStream outputForMainThread = new PipedOutputStream();
new Thread(new Runnable() {
#Override
public void run() {
while(moreDataOnNetwork()) {
byte[] data = readDataFromNetwork();
try {
outputForMainThread.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(new PipedInputStream(outputForMainThread)));
for(String eachLine = reader.readLine(); eachLine != null; eachLine = reader.readLine()) {
System.out.println(eachLine);
}
}
However it almost sounds like you want an event callback mechanism where one thread (your user interface thread) is notified when the other thread detects a certain condition. Depending on your platform much of this is baked in. Using Android, for eg., you could have a thread that determines that a grid entity moved. It would send an update to the main user interface thread to repaint the screen. Such an update could resemble:
public void gridEntityDidUpdate(final Point fromLocation, final Point toLocation) {
Activity activity = getMainActivity();
activity.runOnUiThread(
new Runnable() {
#Override
public void run() {
updateScreen(fromLocation, toLocation);
if(pointsAreCoincedent(fromLocation, toLocation)) {
System.out.println("Hello there!");
}
}
}
);
}
private void updateScreen(Point fromLocation, Point toLocation) {
//Update the main activity screen here
}
In this scenario you have a background thread that works out the position of all on-screen elements and notifies the main thread when elements positions change. There is an extracted method that determines if 2 points are coincidental or the same.
You can use Erlang language to communicated safely among the Processes which runs within there own Address space along with Java as a better and safe alternative to thread.
I've been trying to teach myself concurrency, and I've run into an issue. I understand that two Java threads can communicate to each other via wait() and notify().
The "classic" Java threading tutorials teach wait/notify early on. Back around the Java 1.1, 1.2 time frame that's all there was.
However if you can get a copy of the excellent "Java Concurrency in Practice" by Brian Goetz, wait/notify are not discussed until chapter 14 "Building Custom Synchronizers" in section IV advanced topics. I am severely paraphrasing here, but the impression I got was "OK if you've read the 300 previous pages and none of the building blocks discussed so far meet your needs, then you can try building your own using wait/notify".
My point is that wait/notify, although very important, might not be the best place to start learning concurrency. Some of the answers/comments in this question (producer/consumer, ExecutorService) are referring to the higher level concurrency building blocks that were added in Java 5. Even though this stuff was added later, it's the stuff you should be learning first.
Back to your question - here are a couple of thoughts:
If this is a GUI application and you want to have a background thread do some work, check out SwingWorker. I have had success using a SwingWorker (section 9.3.3) where the background thread reads messages from a blocking queue (section 5.3) does some work and notifies the GUI thread by invoking the higher level "publish" method. No "wait/notify" - at least not in my code.
If the application is not Swing-based and you want to have different threads performing tasks in parallel and occasionally send messages to each other, consider ZeroMQ "The socket library that acts as a concurrency framework." With ZeroMQ, each thread is running an event loop which reads and processes messages. A thread can schedule work on it's own thread by sending itself a message. It can schedule work/notify a different thread by sending a message to that thread (socket).
Anyhow, good luck.
Try using ThreadManager class, which has List<Thread> and is kind of like a semaphore object. Your threads should be able to find and reference other threads from there.
Is it possible to have both threads running simultaneously and still have them listening for notifications from the other?
Whenever they are not waiting, they can be doing something at the same time. If they appear to be just waiting for each other it is likely you are better off with one thread. (Using multiple threads is not always better)
Would this be accomplished through concurrency techniques or instead something like an ActionListener?
It is more likely to be a design issue with how you have broken down the problem. Threads work best when there is a minimum of interaction between them. If they are highly dependent on each other you should consider using less threads.
But as it stands, with the wait/notify paradigm, one of the threads/entities has to simply sit in one cell waiting for another to wander in;
I don't see why you need wait/notify here at all. I would just have them move around and send messages to one another when they are in the same cell.