Icarus said:
I am currently working on creating automatic players for a game, using
Java and alpha beta search. For this, I need to evenly distribute the
processor performance between all automatic players.
I am not really familiar with threads and would like to know if there
is a simple way of managing this. The solution itself shouldn't
As Lew said, no, there just isn't a simple way of doing this. I second
his recommendation of Java Concurrency in Practice.
Here's a link to concurrency in Java to get you started:
<
http://java.sun.com/docs/books/tutorial/essential/concurrency/>
Here's a decent description of the Java Memory Model, which is critical
to understand if you do any work with threads:
<
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html>
Here's a link to Executors, which are your best bet for making things
simple, I think. For your search algorithm, you'll have to return a
result from your worker threads, so it's super important to understand
the Java Memory Model or none of this is going to make a lick of sense
to you:
<
http://java.sun.com/docs/books/tutorial/essential/concurrency/exinter.html>
You'll need to understand Callable and Future well to return a result.
For example, let's say you define some result of your search:
class MyResult {
// ???
}
OK, now you need to return that result from a thread:
class MyTask implements Callable<MyResult> {
public MyResult call() throws Exception {
MyResult result = null;
// do stuff, then:
return result;
}
}
Finally, you need return this result to a "mother thread" that is in
charge of the various sub-threads. I just busy wait here, that's
probably not the best, but gives you the idea.
class ExecutorTest {
public static void test()
throws InterruptedException,
ExecutionException {
ExecutorService es = Executors.newCachedThreadPool();
MyTask myTask = new MyTask();
Future<MyResult> synchResult = es.submit( myTask );
while( !synchResult.isDone() ) {
Thread.sleep(1000); // wait a bit
}
MyResult atLast = synchResult.get();
//...
}
}
Note: syntax checked, not executed. This is safe, I believe, and gives
you an idea how the basic classes work together. More sophisticated
examples might require careful design to keep them as safe as these
classes from the API.
Good luck, and I think we'd all be interested in seeing what you devise
for yourself in the longer run.