Search code examples
javamultithreadingartificial-intelligencebreadth-first-search

how to implement multithreaded Breadth-first search in java?


I've done the breadth-first search in a normal way. now I'm trying to do it in a multithreaded way. i have one queue which is shared between the threads. i use synchronize(LockObject) when i remove a node from the queue ( FIFI queue ) so what I'm trying to do is that. when i thread finds a solution all the other threads will stop immediately.


Solution

  • I've successfully implemented it. what i did is that i took all the nodes in the first level, let's say 4 nodes. then i had 2 threads. each one takes 2 nodes and generate their children. whenever a node finds a solution it has to report the level that it found the solution in and limit the searching level so other threads don't exceed the level.

    only the reporting method should be synchronized.

    i did the code for the coins change problem. this is my code for others to use

    Main Class (CoinsProblemBFS.java)

    package coinsproblembfs;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    import java.util.Scanner;
    
    /**
     *
     * @author Kassem M. Bagher
     */
    public class CoinsProblemBFS
    {
    
        private static List<Item> MoneyList = new ArrayList<Item>();
        private static Queue<Item> q = new LinkedList<Item>();
        private static LinkedList<Item> tmpQ;
        public static Object lockLevelLimitation = new Object();
        public static int searchLevelLimit = 1000;
        public static Item lastFoundNode = null;
        private static int numberOfThreads = 2;
    
        private static void InitializeQueu(Item Root)
        {
            for (int x = 0; x < MoneyList.size(); x++)
            {
                Item t = new Item();
                t.value = MoneyList.get(x).value;
                t.Totalvalue = MoneyList.get(x).Totalvalue;
                t.Title = MoneyList.get(x).Title;
                t.parent = Root;
                t.level = 1;
                q.add(t);
            }
        }
    
        private static int[] calculateQueueLimit(int numberOfItems, int numberOfThreads)
        {
            int total = 0;
            int[] queueLimit = new int[numberOfThreads];
    
            for (int x = 0; x < numberOfItems; x++)
            {
                if (total < numberOfItems)
                {
                    queueLimit[x % numberOfThreads] += 1;
                    total++;
                }
                else
                {
                    break;
                }
            }
            return queueLimit;
        }
    
        private static void initializeMoneyList(int numberOfItems, Item Root)
        {
            for (int x = 0; x < numberOfItems; x++)
            {
                Scanner input = new Scanner(System.in);
                Item t = new Item();
                System.out.print("Enter the Title and Value for item " + (x + 1) + ": ");
                String tmp = input.nextLine();
                t.Title = tmp.split(" ")[0];
                t.value = Double.parseDouble(tmp.split(" ")[1]);
                t.Totalvalue = t.value;
                t.parent = Root;
                MoneyList.add(t);
            }
        }
    
        private static void printPath(Item item)
        {
            System.out.println("\nSolution Found in Thread:" + item.winnerThreadName + "\nExecution Time: " + item.searchTime + " ms, " + (item.searchTime / 1000) + " s");
            while (item != null)
            {
                for (Item listItem : MoneyList)
                {
                    if (listItem.Title.equals(item.Title))
                    {
                        listItem.counter++;
                    }
                }
                item = item.parent;
            }
            for (Item listItem : MoneyList)
            {
                System.out.println(listItem.Title + " x " + listItem.counter);
            }
    
        }
    
        public static void main(String[] args) throws InterruptedException
        {
            Item Root = new Item();
            Root.Title = "Root Node";
            Scanner input = new Scanner(System.in);
            System.out.print("Number of Items: ");
            int numberOfItems = input.nextInt();
            input.nextLine();
    
            initializeMoneyList(numberOfItems, Root);
    
            
            System.out.print("Enter the Amount of Money: ");
            double searchValue = input.nextDouble();
            int searchLimit = (int) Math.ceil((searchValue / MoneyList.get(MoneyList.size() - 1).value));
            System.out.print("Number of Threads (Muste be less than the number of items): ");
            numberOfThreads = input.nextInt();
    
            if (numberOfThreads > numberOfItems)
            {
                System.exit(1);
            }
    
            InitializeQueu(Root);
    
            int[] queueLimit = calculateQueueLimit(numberOfItems, numberOfThreads);
            List<Thread> threadList = new ArrayList<Thread>();
    
            for (int x = 0; x < numberOfThreads; x++)
            {
                tmpQ = new LinkedList<Item>();
                for (int y = 0; y < queueLimit[x]; y++)
                {
                    tmpQ.add(q.remove());
                }
                BFS tmpThreadObject = new BFS(MoneyList, searchValue, tmpQ);
                Thread t = new Thread(tmpThreadObject);
                t.setName((x + 1) + "");
                threadList.add(t);
            }
    
            for (Thread t : threadList)
            {
                t.start();
            }
    
            boolean finish = false;
    
            while (!finish)
            {
                Thread.sleep(250);
                for (Thread t : threadList)
                {
                    if (t.isAlive())
                    {
                        finish = false;
                        break;
                    }
                    else
                    {
                        finish = true;
                    }
                }
            }
            printPath(lastFoundNode);
    
        }
    }
    

    Item Class (Item.java)

    package coinsproblembfs;
    
    /**
     *
     * @author Kassem
     */
    public class Item
    {
        String Title = "";
        double value = 0;
        int level = 0;
        double Totalvalue = 0;
        int counter = 0;
        Item parent = null;
        long searchTime = 0;
        String winnerThreadName="";
    }
    

    Threads Class (BFS.java)

    package coinsproblembfs;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    
    /**
     *
     * @author Kassem M. Bagher
     */
    public class BFS implements Runnable
    {
    
        private LinkedList<Item> q;
        private List<Item> MoneyList;
        private double searchValue = 0;
        private long start = 0, end = 0;
    
        public BFS(List<Item> monyList, double searchValue, LinkedList<Item> queue)
        {
            q = new LinkedList<Item>();
            MoneyList = new ArrayList<Item>();
            this.searchValue = searchValue;
            for (int x = 0; x < queue.size(); x++)
            {
                q.addLast(queue.get(x));
            }
            for (int x = 0; x < monyList.size(); x++)
            {
                MoneyList.add(monyList.get(x));
            }
        }
    
        private synchronized void printPath(Item item)
        {
    
            while (item != null)
            {
                for (Item listItem : MoneyList)
                {
                    if (listItem.Title.equals(item.Title))
                    {
                        listItem.counter++;
                    }
                }
                item = item.parent;
            }
            for (Item listItem : MoneyList)
            {
                System.out.println(listItem.Title + " x " + listItem.counter);
            }
        }
    
        private void addChildren(Item node, LinkedList<Item> q, boolean initialized)
        {
            for (int x = 0; x < MoneyList.size(); x++)
            {
                Item t = new Item();
                t.value = MoneyList.get(x).value;
                if (initialized)
                {
                    t.Totalvalue = 0;
                    t.level = 0;
                }
                else
                {
                    t.parent = node;
                    t.Totalvalue = MoneyList.get(x).Totalvalue;
                    if (t.parent == null)
                    {
                        t.level = 0;
                    }
                    else
                    {
                        t.level = t.parent.level + 1;
                    }
                }
                t.Title = MoneyList.get(x).Title;
                q.addLast(t);
            }
        }
    
        @Override
        public void run()
        {
            start = System.currentTimeMillis();
            try
            {
                while (!q.isEmpty())
                {
                    Item node = null;
                    node = (Item) q.removeFirst();
                    node.Totalvalue = node.value + node.parent.Totalvalue;
                    if (node.level < CoinsProblemBFS.searchLevelLimit)
                    {
                        if (node.Totalvalue == searchValue)
                        {
                            synchronized (CoinsProblemBFS.lockLevelLimitation)
                            {
                                CoinsProblemBFS.searchLevelLimit = node.level;
                                CoinsProblemBFS.lastFoundNode = node;
                                end = System.currentTimeMillis();
                                CoinsProblemBFS.lastFoundNode.searchTime = (end - start);
                                CoinsProblemBFS.lastFoundNode.winnerThreadName=Thread.currentThread().getName();
                            }
                        }
                        else
                        {
                            if (node.level + 1 < CoinsProblemBFS.searchLevelLimit)
                            {
                                addChildren(node, q, false);
                            }
                        }
                    }
                }
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    

    Sample Input:

    Number of Items: 4
    Enter the Title and Value for item 1: one 1
    Enter the Title and Value for item 2: five 5
    Enter the Title and Value for item 3: ten 10
    Enter the Title and Value for item 4: twenty 20
    Enter the Amount of Money: 150
    Number of Threads (Muste be less than the number of items): 2