Jacobvu84 / serenity-pageobject-junit-webdriver

4 stars 1 forks source link

Research Parallel With Blocking Queue #80

Open Jacobvu84 opened 3 years ago

Jacobvu84 commented 3 years ago
package vu.jacob.features.javas;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ResearchParallelWithBlockingQueue {

    private static BlockingQueue<Thread> webDriverBlockingQueue;

    private static final int DEFAULT_WEB_DRIVER_COUNT = 2;

    public static void main(String[] args) throws InterruptedException {

        // Creating 3 threads, passing thread name as arg
        Thread t1 = new Thread(new StartWebDriver(), "webdriver 1");
        Thread t2 = new Thread(new StartWebDriver(), "webdriver 2");
        Thread t3 = new Thread(new StartWebDriver(), "webdriver 3");
        Thread t4 = new Thread(new StartWebDriver(), "webdriver 4");
        Thread t5 = new Thread(new StartWebDriver(), "webdriver 5");

        List<Thread> allThreal = new ArrayList<>();

        allThreal.add(t1);
        allThreal.add(t2);
        allThreal.add(t3);
        allThreal.add(t4);
        allThreal.add(t5);

        // Runtime.getRuntime().addShutdownHook(new Thread(this::dismissAll));

        webDriverBlockingQueue = new LinkedBlockingQueue<>(DEFAULT_WEB_DRIVER_COUNT);

        allThreal.forEach(thread -> {
            try {
                PutObjectToTheQueue(thread);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        webDriverBlockingQueue.parallelStream().forEach(action -> {
            action.run();
        });

    }

    private static void PutObjectToTheQueue(Thread thread) throws InterruptedException {
        while (webDriverBlockingQueue.size() < DEFAULT_WEB_DRIVER_COUNT) {
            System.out.println("BlockingQueueWebDriverPool, Queue was successfully created  with size = {}: "
                    + webDriverBlockingQueue.size());

            webDriverBlockingQueue.put(thread);
        }
    }
}

class StartWebDriver implements Runnable {

    @Override
    public void run() {
        // Getting thread's name
        for (int i = 0; i < 5; i++) {

            System.out.println("Current Thread Name- " + Thread.currentThread().getId() + " ====>" + i);
        }

    }

}