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 6793365
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T18:05:31+00:00 2026-05-26T18:05:31+00:00

public class SieveGenerator{ static int N = 50; public static void main(String args[]){ int

  • 0
public class SieveGenerator{

static int N = 50;
public static void main(String args[]){

    int cores = Runtime.getRuntime().availableProcessors();

    int f[] = new int[N];

    //fill array with 0,1,2...f.length
    for(int j=0;j<f.length;j++){
        f[j]=j;
    }

    f[0]=0;f[1]=0;//eliminate these cases

    int p=2;

    removeNonPrime []t = new removeNonPrime[cores];

    for(int i = 0; i < cores; i++){
        t[i] = new removeNonPrime(f,p);
    }

    while(p <= (int)(Math.sqrt(N))){
        t[p%cores].start();//problem here because you cannot start a thread which has already started(IllegalThreadStateException)
        try{
            t[p%cores].join();
        }catch(Exception e){}
        //get the next prime
        p++;
        while(p<=(int)(Math.sqrt(N))&&f[p]==0)p++;
    }


    //count primes
    int total = 0;
    System.out.println();

    for(int j=0; j<f.length;j++){
        if(f[j]!=0){
            total++;
        }
    }
    System.out.printf("Number of primes up to %d = %d",f.length,total);
}
}


class removeNonPrime extends Thread{
int k;
int arr[];

public removeNonPrime(int arr[], int k){
    this.arr = arr;
    this.k = k;
}

public void run(){
    int j = k*k;
    while(j<arr.length){
        if(arr[j]%k == 0)arr[j]=0;
        j=j+arr[k];

    }
}
}

Hi I’m getting an IllegalThreadStateException when I run my code and I’ve figured it’s because I am trying to start a thread that has already been started. So how could I kill
or stop the thread each time, to get around this problem?

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

    how could I kill or stop the thread each time, to get around this problem?

    The answer is, you can’t. Once started, a Thread may not be restarted. This is clearly documented in the javadoc for Thread. Instead, what you really want to do is new an instance of RemoveNonPrime each time you come around in your loop.

    You have a few other problems in your code.
    First, you need to increment p before using it again:

    for(int i = 0; i < cores; i++){
        t[i] = new removeNonPrime(f,p); //<--- BUG, always using p=2 means only multiples of 2 are cleared
    }
    

    Second, you might be multithreaded, but you aren’t concurrent. The code you have basically only allows one thread to run at a time:

    while(p <= (int)(Math.sqrt(N))){
        t[p%cores].start();//
        try{
            t[p%cores].join(); //<--- BUG, only the thread which was just started can be running now
        }catch(Exception e){}
        //get the next prime
        p++;
        while(p<=(int)(Math.sqrt(N))&&f[p]==0)p++;
    }
    

    Just my $0.02, but what you are trying to do might work, but the logic for selecting the next smallest prime will not always pick a prime, for example if one of the other threads hasn’t processed that part of the array yet.

    Here is an approach using an ExecutorService, there are some blanks (…) that you will have to fill in:

    /* A queue to trick the executor into blocking until a Thread is available when offer is called */
    public class SpecialSyncQueue<E> extends SynchronousQueue<E> {
        @Override
        public boolean offer(E e) {
            try {
                put(e);
                return true;
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
    }
    
    ExecutorService executor = new ThreadPoolExecutor(cores, cores, new SpecialSyncQueue(), ...);
    void pruneNonPrimes() {
        //...
        while(p <= (int)(Math.sqrt(N))) {
            executor.execute(new RemoveNonPrime(f, p));
            //get the next prime
            p++;
            while(p<=(int)(Math.sqrt(N))&&f[p]==0)p++;
        }
    
    
        //count primes
        int total = 0;
        System.out.println();
    
        for(int j=0; j<f.length;j++){
            if(f[j]!=0){
                total++;
            }
        }
        System.out.printf("Number of primes up to %d = %d",f.length,total);
    }
    
    
    
    class RemoveNonPrime extends Runnable {
        int k;
        int arr[];
    
        public RemoveNonPrime(int arr[], int k){
            this.arr = arr;
            this.k = k;
        }
    
        public void run(){
            int j = k*k;
            while(j<arr.length){
                if(arr[j]%k == 0)arr[j]=0;
                j+=k;
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

public class Test { public static void main(String[] args) { int[] arr = new
public class Asterisk { public static void main(String[] args) { String output=""; int count=1,
public class Main { public static void main(String[] args){ XClass x = new XClass();
public class Test { public static void main(String[] args) { } } class Outer
public class doublePrecision { public static void main(String[] args) { double total = 0;
public class WrapperTest { public static void main(String[] args) { Integer i = 100;
public class Main3 { public static void main(String[] args) { Integer min = Integer.MIN_VALUE;
public class Empty { public static void main( String[] args ) { TreeSet<Class> classes
public class Test { Integer i; int j; public static void main ( String
public class prime { public static void main(String[] args) { long thing = 600851475143L;

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.