Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

multithreading - Get and send messages with Java Threads

I want to make a thread, which runs, computes something with the data i give it, and returns a few values, or an object. The thread is a part of a Swing GUI.

My question: How can I make a method that runs when I make the thread, and returns an object (or whatever I want it to return)?

My code:

private void nextTurn () {
    // do something
    if (turn == white) {
        try {
            Engine e = new Engine(); // Engine is implemented by runnable
            e.start();
            Move m = e.getBestMove (board);
            // thread should work, next code should be excecuted immediately
        }
        catch (Exception e) {}
    }

    // end of Main class
}

This is the first time I am working with Threads, and I know you should avoid them if possible, but I need it this time for my GUI. The info on the Oracle site on Threads did not help me out. I am able to make a program with multiple Threads that runs indefinately, but I can't make it work with functions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I suggest you use an ExecutorService. It allows you to create a thread pool, you can pass tasks to it and get the results later.

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...