Organiccat
Organiccat

Reputation: 5651

Pass data to another thread, java

I'm creating a small application learning about Java threading. I want to have a thread running that will analyze a small piece of data (a poker hand), and output a display message when the hand is detected to be a winning hand.

I already have the part completed that generates hands until the deck is empty, I just need to figure out how to pass that data over into the other thread which analyzes and triggers the display message (just a simple System.out).

I'd like to do this to a currently running thread, instead of spawning a new thread for every hand that is dealt and passing the cards in the constructor.

public static void main(String[] args) {
        Deck myDeck = new PokerDeck();
        DeckHandlerInterface deckHandler = new DeckHandler();

        (new Thread(new ThreadWin())).start();

        for(int x = 0; x < 2; x++) {
            while(myDeck.getDeck().size() >= deckHandler.getHandSize()) {
                deckHandler.dealHand(myDeck.getDeck());
            }
                    deckHandler.resetDeck();
        }

    }

My deckHandler returns a collection object which is what I want to pass to the other thread. That's the part I'm not sure how to do.

Upvotes: 1

Views: 1138

Answers (4)

Krystian Lieber
Krystian Lieber

Reputation: 481

You can use BlockingQueue to create simple consumer-producer scenario, there is even a simple example in the documentation.

You should also read this to have a better understanding of concurrency.

Propably the best method is to use java.util.concurrent package threadpool to execute tasks. Threadpool are nice, easy to implement, but you will not learn much apart from using the threadpools.

Upvotes: 0

Ivan
Ivan

Reputation: 1256

It sounds like you may want your "ThreadWin" to observe (http://en.wikipedia.org/wiki/Observer_pattern) the DeckHandler

Basically, the ThreadWin thread will "register" with the DeckHandler so it gets notified when the DeckHandler gets a new batch of PokerHands.

When the ThreadWin thread is notified it will "stop resting" and determine which hand was best.

Upvotes: 0

Keppil
Keppil

Reputation: 46209

There are many ways to accomplish this.

A simple approach might be to create a Queue that you pass in a reference to via the ThreadWin constructor.
Then you just add the objects you wish to pass to the queue from the main thread, and listen for new objects on the queue in your ThreadWin thread. In particular it seems like a BlockingQueue might be a good fit here.

Upvotes: 1

Mike B
Mike B

Reputation: 5451

You probably want to use a couple of BlockingQueues. Have the thread that generates hands stick the hands in one queue. The thread checking hands polls that queue and checks any hands it finds. Then it writes the results to a 2nd queue which the hand-generating thread can poll and display.

Upvotes: 2

Related Questions