Saturday, September 27, 2014

Sample Threading

import java.util.HashMap;
import java.util.Vector;

public class AutoPlayer implements Runnable {

    private RequestDispatcher requestDispatcher;

    public AutoPlayer(RequestDispatcher requestDispatcher) {
    this.requestDispatcher = requestDispatcher;
    }


    public static void main(String[] args) {

    HashMap<String, Game> games = new HashMap<String, Game>();

    RequestDispatcher rd = new RequestDispatcher(games);

    Vector<Thread> threads = new Vector<Thread>();

    for (int i = 0; i < 10; i++) {
        AutoPlayer autoPlayer = new AutoPlayer(rd);
        Thread thread = new Thread(autoPlayer);
        threads.add(thread);
        thread.start();
    }

    for (int i = 0; i < threads.size(); i++) {
        try {
        threads.get(i).join();
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
    }

    }



    @Override
    public void run() {

    PlayResponse response = null;

    for (int i = 0; i < 1000; i++) {
        byte[] numbers = requestDispatcher.cardRequest();

        try {
        response = new PlayResponse();
        requestDispatcher.process("Lucky", 10, numbers, response);
        } catch (UnknownGameException e) {
        e.printStackTrace();
        }

        if (response != null) {
        System.out.println("[" + Thread.currentThread() + "] total requests:" + requestDispatcher.generatedCards);
        }
    }
    }

}

No comments:

Post a Comment