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

  • SEARCH
  • Home
  • 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 63085
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T18:34:38+00:00 2026-05-10T18:34:38+00:00

I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency

  • 0

I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I’m only interested in the thread part.

//code without thread use public static int getNextPrime(int from) {     int nextPrime = from+1;     boolean superPrime = false;     while(!superPrime) {         boolean prime = true;         for(int i = 2;i < nextPrime;i++) {             if(nextPrime % i == 0) {                 prime = false;             }         }         if(prime) {             superPrime = true;         } else {             nextPrime++;         }     }     return nextPrime; }  public static void main(String[] args) {    int primeStart = 5;    ArrayList list = new ArrayList();    for(int i = 0;i < 10000;i++) {        list.add(primeStart);        primeStart = getNextPrime(primeStart);    } } 

If I’m running the code like this and it takes about 56 seconds. If, however, I have the following code (as an alternative):

public class PrimeRunnable implements Runnable {      private int from;     private int lastPrime;      public PrimeRunnable(int from) {         this.from = from;     }      public boolean isPrime(int number) {         for(int i = 2;i < from;i++) {             if((number % i) == 0) {                 return false;             }         }         lastPrime = number;         return true;     }      public int getLastPrime() {         return lastPrime;     }      public void run() {         while(!isPrime(++from))             ;     } }  public static void main(String[] args) {    int primeStart = 5;    ArrayList list = new ArrayList();    for(int i = 0;i < 10000;i++) {      PrimeRunnable pr = new PrimeRunnable(primeStart);      Thread t = new Thread(pr);      t.start();      t.join();      primeStart = pr.getLastPrime();      list.add(primeStart);    } } 

The whole operation takes about 7 seconds. I am almost certain that even though I only create one thread at a time, a thread doesn’t always finish when another is created. Is that right? I am also curious: why is the operation ending so fast?

When I’m joining a thread, do other threads keep running in the background, or is the joined thread the only one that’s running?

  • 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. 2026-05-10T18:34:39+00:00Added an answer on May 10, 2026 at 6:34 pm

    By putting the join() in the loop, you’re starting a thread, then waiting for that thread to stop before running the next one. I think you probably want something more like this:

    public static void main(String[] args) {    int primeStart = 5;     // Make thread-safe list for adding results to    List list = Collections.synchronizedList(new ArrayList());     // Pull thread pool count out into a value so you can easily change it    int threadCount = 10000;    Thread[] threads = new Thread[threadCount];     // Start all threads    for(int i = 0;i < threadCount;i++) {      // Pass list to each Runnable here      // Also, I added +i here as I think the intention is       //    to test 10000 possible numbers>5 for primeness -       //    was testing 5 in all loops      PrimeRunnable pr = new PrimeRunnable(primeStart+i, list);      Thread[i] threads = new Thread(pr);      threads[i].start();  // thread is now running in parallel    }     // All threads now running in parallel     // Then wait for all threads to complete    for(int i=0; i<threadCount; i++) {      threads[i].join();    } } 

    By the way pr.getLastPrime() will return 0 in the case of no prime, so you might want to filter that out before adding it to your list. The PrimeRunnable has to absorb the work of adding to the final results list. Also, I think PrimeRunnable was actually broken by still having incrementing code in it. I think this is fixed, but I’m not actually compiling this.

    public class PrimeRunnable implements Runnable {         private int from;     private List results;   // shared but thread-safe      public PrimeRunnable(int from, List results) {         this.from = from;         this.results = results;     }      public void isPrime(int number) {         for(int i = 2;i < from;i++) {                 if((number % i) == 0) {                         return;                 }         }         // found prime, add to shared results         this.results.add(number);     }      public void run() {         isPrime(from);      // don't increment, just check one number     }     } 

    Running 10000 threads in parallel is not a good idea. It’s a much better idea to create a reasonably sized fixed thread pool and have them pull work from a shared queue. Basically every worker pulls tasks from the same queue, works on them and saves the results somewhere. The closest port of this with Java 5+ is to use an ExecutorService backed by a thread pool. You could also use a CompletionService which combines an ExecutorService with a result queue.

    An ExecutorService version would look like:

    public static void main(String[] args) {    int primeStart = 5;     // Make thread-safe list for adding results to    List list = Collections.synchronizedList(new ArrayList());     int threadCount = 16;  // Experiment with this to find best on your machine    ExecutorService exec = Executors.newFixedThreadPool(threadCount);     int workCount = 10000;  // See how # of work is now separate from # of threads?    for(int i = 0;i < workCount;i++) {      // submit work to the svc for execution across the thread pool       exec.execute(new PrimeRunnable(primeStart+i, list));    }     // Wait for all tasks to be done or timeout to go off    exec.awaitTermination(1, TimeUnit.DAYS); } 

    Hope that gave you some ideas. And I hope the last example seemed a lot better than the first.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 73k
  • Answers 73k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer Try using Firefox with Firebug ('view generated source') and see… May 11, 2026 at 2:11 pm
  • added an answer Something like: Total = dsPoint.Tables['DataTable1'].Compute('SUM(columnName)', String.Empty); You provide the columnName… May 11, 2026 at 2:11 pm
  • added an answer Edited: after testing, Notepad++ doesn't support the {n} method of… May 11, 2026 at 2:11 pm

Related Questions

I have some code for starting a thread on the .NET CF 2.0: ThreadStart
I have some code that will be accessed from two threads: class Timer{ public:
I have inherited a middle tier system with some multi-Threading issues. Two different threads,
I have some UI in VB 2005 that looks great in XP Style, but
Another synchronization question...I hope you guys don't get annoyed ;) Assume the following scenario:
Should I use old synchronized Vector collection, ArrayList with synchronized access or Collections.synchronizedList or
I have posted several questions related to this problem I am having and I
As part of a large automation process, we are calling a third-party API that

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.