Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6978155
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T17:43:08+00:00 2026-05-27T17:43:08+00:00

I’ve done the breadth-first search in a normal way. now I’m trying to do

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T17:43:09+00:00Added an answer on May 27, 2026 at 5:43 pm

    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
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,
I have a text area in my form which accepts all possible characters from
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I used javascript for loading a picture on my website depending on which small

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.