Threads for long computations?

I want to just play around with AI for a bit now. I want to see if I can make a relatively decent chess AI. It will probably not work, but whatever.

In any case, when I make a game, I have it work through a series of “ticks,” that is every 60th of a second the game “ticks,” runs through all of it’s code, then will tick again later.

Usually my computations are very small, so it runs just fine. However, what if I want to do 5 seconds worth of computations before the computer moves? I would want the game to continue “ticking” 60 times a second, except be running it’s computations in the background.

Now, I know about threads and whatnot, but I don’t understand how to implement them into my code in this sort of situation. Could anybody point me in a direction, or give me some tips for going in such a direction?

Thanks

A basic thread is relatively simple in Java, using the Thread class.

The idea is you create a new Thread object and pass it an object that implements the Runnable interface:

Thread t = new Thread(runnableObject);

The Runnable interface has a single method you must implement called run(). This is the code that’ll run in a separate thread. To execute it, you do start:

t.start();

And that’s all there is to it. Again, at a basic level. This should be enough, if all you need to do is run some calculations in a separate thread.

It’s hard to believe it’s so simple :stuck_out_tongue:
I’ll give it a shot, thanks

Check this out for more details on concurrency and the Thread class: http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html

Here is an example with Futures.

import java.util.concurrent.Future;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Callable;

public class Test {
    
    static int fib(int n) {
        if(n < 2) return n;
        else return fib(n-1) + fib(n-2);
    }
    
    public static void main(String[] args) throws Exception {
        ForkJoinPool pool = new ForkJoinPool();
        Future<Integer> future = pool.submit(new Callable<Integer>() {
            public Integer call() {
                System.out.println(Thread.currentThread());
                return fib(45);
            }
        });
        System.out.println(Thread.currentThread());
        while(!future.isDone()) {
            System.out.println("running");
            Thread.sleep(500);
        }
        System.out.println(future.get());
    }
}