How can I kill all Threads of the same class from within the run() method?

Ok
I have a class called Consumer that extends Thread
I have several Consumer threans running... but, when a certain condition is true (within the run() method) in ANY of the threads, I want to kill ALL the threads of that object.
is this possible?

I know this is gonna be too demanding, but can someone please tell me why my Consumer's run() method never reaches the System.out.println( "ALL CONSUMING DONE") line
Create a multi-threaded prime number calculator that is based on the producer-consumer model
using semaphores. Your program should be able to check for prime numbers in a range specified
by the user and with a variable number of threads. Example:
$ java PrimeFind 3 5000 10000
should use 1 producer and 2 consumers (3 threads in total, obviously the minimum is 2) to find all
the prime numbers in the range [5000,10000].
The producer should: use a buffer to store candidate numbers that have to be checked for
primality.
Consumers should: read from the buffer, check if a number is prime and update the status of the
program accordingly (e.g. show the number on the screen, or save it to a file)
import java.util.concurrent.Semaphore;
import java.io.*;
public class Assign1 {
static int fromThisNumber;
static int toThisNumber;
static int numberOfThreads;
static int buffer[];
static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                     an "OK" to the consumers*/
static Semaphore critical;  /*This is a Mutex semaphore. It allows only 1 consumer
                                     to enter his critical section.
static Semaphore counter;     /*This semaphore acts as a counter.
                                    Instead of having a global variable
                                     incremented each time, we just release()
                                     this semephore when we find a prime number
                                     Because remember that release() increments permits
static Producer prod;
static Consumer cons[];
static int in=0;
static int out=0;
static PrintWriter outFile;
     public static void main (String args[]){
          try{
               outFile=new PrintWriter(new FileWriter("primes.txt"));
               }catch(Exception e){}
          numberOfThreads=Integer.parseInt(args[0]);
          fromThisNumber=Integer.parseInt(args[1]);
          toThisNumber=Integer.parseInt(args[2]);
          buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
          ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                  for the Producer to produce atleast a
                                                  item. Suppose ready was 1 and if
                                                  Consumer ran first he would be in an
                                                  empty buffer */
          critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                     the first Consumer thread tries
                                                     to enter its critical section, it
                                                     should be allowed to;
                                                     Subsequent threads will have to
                                                     wait since only 1 thread can
                                                     access its critical section at a time*/
          counter=new Semaphore(0,false); // duh!
          cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                            is taken by the Producer*/
          //Creating Producer object
          prod=new Producer();
          //Creating the Consumer object and start the thread.
          for(int i=0;i<cons.length;i++)
                    cons=new Consumer();
                    cons[i].start();
          prod.start();          
          //Printing to screen and file
/*          for(int i=0;i<buffer.length;i++)
               if(buffer[i]!=0)
                         System.out.println(buffer[i]);
                         outFile.println(buffer[i]);
          System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
          outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
          outFile.close();*/                    
static class Producer extends Thread {
     public void run(){try{
          while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
               {     System.out.println("producing");     
                    buffer[in]=fromThisNumber;
                    in++;
                    fromThisNumber++;
                    ready.release();
          catch (Exception e){e.printStackTrace();}
          System.out.println("ALL PRODUCING DONE");
static class Consumer extends Thread {
     int tempout=0;
     public void run(){try{
          System.out.println("before while"+this.getId());
          while(tempout<=in)
               System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
               ready.acquire();
               System.out.println("before critical.acquire"+this.getId());
               critical.acquire();
               tempout=out;
               out++;
               critical.release();               
               if(!isPrime(buffer[tempout]))
                    {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
               else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
               critical.acquire();
               tempout=out;
               System.out.println("tempout:"+tempout+" of "+this.getId());
               critical.release();
          System.out.println("ALL CONSUMING DONE"+this.getId());
     catch(Exception e){e.printStackTrace();}
     //Prime number-checking method     
     public boolean isPrime(int n){
          for(int i=2;i<=(n/2);i++)
               if(n%i==0)
                    return false;
          return true;
======================
import java.util.concurrent.Semaphore;
import java.io.*;
/* 3 questions to ask Barlas
* Why error if I start the Consumer threads before Producer
* Why does the counter semaphore always give a +1 result at the end
* Is there a way I can verify that all the work is not being done by only 1 consumer thread? In other words, the workload is being shared properly
* if I put ready.acquire() outside or inside the while loop, its not making any difference, why?
* Strangely, its not making any difference if I playing with the release() and aquire() of the semaphores, WHY?!?!
public class Assign1 {
static int fromThisNumber;
static int toThisNumber;
static int numberOfThreads;
static int buffer[];
static Semaphore ready;          /*This semaphore is used by the Producer to signal
                                   an "OK" to the consumers*/
static Semaphore critical; /*This is a Mutex semaphore. It allows only 1 consumer
                                   to enter his critical section.
static Semaphore counter;     /*This semaphore acts as a counter.
                              Instead of having a global variable
                                   incremented each time, we just release()
                                   this semephore when we find a prime number
                                   Because remember that release() increments permits
static Producer prod;
static Consumer cons[];
static int in=0;
static int out=0;
static PrintWriter outFile;
     public static void main (String args[]){
          try{
               outFile=new PrintWriter(new FileWriter("primes.txt"));
               }catch(Exception e){}
          numberOfThreads=Integer.parseInt(args[0]);
          fromThisNumber=Integer.parseInt(args[1]);
          toThisNumber=Integer.parseInt(args[2]);
          buffer=new int[Integer.parseInt(args[2])-Integer.parseInt(args[1])+1];
          ready=new Semaphore(0,false); /*We initialise it to 0 because we wait
                                                  for the Producer to produce atleast a
                                                  item. Suppose ready was 1 and if
                                                  Consumer ran first he would be in an
                                                  empty buffer */
          critical=new Semaphore (1,false);/*We initialise it to 1 because when
                                                  the first Consumer thread tries
                                                  to enter its critical section, it
                                                  should be allowed to;
                                                  Subsequent threads will have to
                                                  wait since only 1 thread can
                                                  access its critical section at a time*/
          counter=new Semaphore(0,false); // duh!
          cons=new Consumer[numberOfThreads-1]; /*numberOfThreads-1 because 1 thread
                                                            is taken by the Producer*/
          //Creating Producer object
          prod=new Producer();
          //Creating the Consumer object and start the thread.
          for(int i=0;i<cons.length;i++)
                    cons[i]=new Consumer();
                    cons[i].start();
          prod.start();          
          //Printing to screen and file
/*          for(int i=0;i<buffer.length;i++)
               if(buffer[i]!=0)
                         System.out.println(buffer[i]);
                         outFile.println(buffer[i]);
          System.out.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits()+"\n primes.txt written");
          outFile.println("Total primes found between "+args[1]+" and "+toThisNumber+": "+counter.availablePermits());
          outFile.close();*/                    
static class Producer extends Thread {
     public void run(){try{
          while(in<buffer.length)     /*'in' should always be more than 'out'.Oherwise the consumer will try to access an empty index*/
               {     System.out.println("producing");     
                    buffer[in]=fromThisNumber;
                    in++;
                    fromThisNumber++;
                    ready.release();
          catch (Exception e){e.printStackTrace();}
          System.out.println("ALL PRODUCING DONE");
static class Consumer extends Thread {
     int tempout=0;
     public void run(){try{
          System.out.println("before while"+this.getId());
          while(tempout<=in)
               System.out.println("before ready"+this.getId()+" "+ready.availablePermits()+" "+in);
               ready.acquire();
               System.out.println("before critical.acquire"+this.getId());
               critical.acquire();
               tempout=out;
               out++;
               critical.release();               
               if(!isPrime(buffer[tempout]))
                    {System.out.println(buffer[tempout]+" by "+this.getId());buffer[tempout]=0;}
               else {counter.release();System.out.println("prime added: "+buffer[tempout]+" by "+this.getId());}
               critical.acquire();
               tempout=out;
               System.out.println("tempout:"+tempout+" of "+this.getId());
               critical.release();
          System.out.println("ALL CONSUMING DONE"+this.getId());
     catch(Exception e){e.printStackTrace();}
     //Prime number-checking method     
     public boolean isPrime(int n){
          for(int i=2;i<=(n/2);i++)
               if(n%i==0)
                    return false;
          return true;
===========================
BTW, when I tried to change extends Thread to implements Runnable I got some kinda of error.
Actually, my program is pretty complete... its just that something if messed up in my Consumer's run() method's while loop... I think
I know guys its crazy to ask ya'll to look at so much code, but.... I'd really appreciate it. This assignment is killing me, been at it since 10 hours now....

Similar Messages

  • When importing songs of a same album but different artist iTunes will separate the artists. How can I bring all together in the same album?

    When importing songs of a same album but different artist iTunes will separate the artists. How can I bring all together in the same album?

    Generally setting a common Album Artist will fix things. For deeper problems see Grouping tracks into albums.
    tt2

  • I have three different listings for Bob Seger on my iPod (bob Seger, Bob Seger System and Bob Seger and The Silver Bullet Band) How can I put all 3 in the same artist folder without changing artist name?

    I have three different listings for Bob Seger on my iPod (Bob Seger, Bob Seger System and Bob Seger and The Silver Bullet Band) How can I put all 3 in the same artist folder without changing artist name?

    Can you just create a new "Playlist", name it Bob Seger and drag what you want into the Playlist.
    File/New Playlist

  • I unfortunately just got my IPhone 4s stolen.I thought I had the find my iPhone enabled but I didn't because I cannot locate the phone when I sign in ICloud.How can I erase all data on the phone so the thief can't access my personal information.

    I unfortunately just got my IPhone 4s stolen.I thought I had the find my iPhone enabled but I didn't because I cannot locate the phone when I sign in ICloud.I have a password on the phone but i'm not sure if I turned on the option where the phone resets if you incorrectly put the password more than ten time. I immediately called my phone company (Verizon) and reported the phone stolen.So I know whoever took the phone cannot place calls or use the phone. But can they still access my data on the phone if they manage to unlock the phone?  If so how can I erase all data on the phone so the thief can't access my personal information? is there any other way other than Find my IPhone to wipe off the data on the phone? I really don't want my personal information such as pictures, text messages, notes and social networks profile available to a stranger!!? Help please!!!

        Hello thewrongway,
    I'm sorry to hear about your phone!  I understand the need for an active device. You are able to activate an old device and process an insurance claim for your iPhone 4s within 60days from the incident date.  Keep in mind if the old phone is not a smartphone and you currently have unlimited data that feature will fall off.  If you have a tier data plan no changes will be made.  Please let me know if you have any additional questions.  Thank you.   
    TominqueBo
    VZW Support
    Follow us on Twitter at @VZWSupport

  • On I-Mac, how can I close all tabs at the same time?

    On I-Mac, how can I close all tabs at the same time?
    I use Mozilla Firefox for internet.

    Not an Apple product, have you visited:
    https://support.mozilla.org/en-US/kb/keyboard-shortcuts-perform-firefox-tasks-qu ickly

  • I bought a mac air retina to replace a mac pro. How can I get all files of the back up and copy them to the new mac?

    I bought a mac air retina to replace a mac pro. How can I get all files of the back up and copy them to the new mac?

    Mail window may be in the Full Screen mode.
    Move the mouse pointer to the top right corner of the Mail window and hold it there.
    Menu bar should drop down and click the blue double arrow icon.
    Full Screen toggle shortcut:  control + command + F

  • How can I tell all PCs has the DAU installed?

    I am running ZCM 10.3 on SLES 10. I have enabled patch management and I saw the DAU has version 38. How can I tell version 38 is the latest DAU for ZCM 10.3.
    Also, how can I tell all devices have the latest DAU installed? I came across a few devices have problem with ZCM agent and after I fixed the issue, I saw it started to install the DAU. However, if I have not touched that managed devices, I would not know there is a problem. Can I check all devices status with DAU on ZCC?
    Regards
    Andy

    andyj2009,
    It appears that in the past few days you have not received a response to your
    posting. That concerns us, and has triggered this automated reply.
    Has your problem been resolved? If not, you might try one of the following options:
    - Visit http://support.novell.com and search the knowledgebase and/or check all
    the other self support options and support programs available.
    - You could also try posting your message again. Make sure it is posted in the
    correct newsgroup. (http://forums.novell.com)
    Be sure to read the forum FAQ about what to expect in the way of responses:
    http://forums.novell.com/faq.php
    If this is a reply to a duplicate posting, please ignore and accept our apologies
    and rest assured we will issue a stern reprimand to our posting bot.
    Good luck!
    Your Novell Product Support Forums Team
    http://support.novell.com/forums/

  • How can I delete all items on the "Done" list in Reminer-App? There are meanwhile hundreds of items (shopping, appoitments, ...) and I don't want to spend hours deleting them.

    How can I delete all items on the "Done" list in Reminer-App? There are meanwhile hundreds of items (shopping, appoitments, ...) and I don't want to spend hours deleting them.

    You can't remove the built-in root certificates, but you can remove their trust bits via the Edit button to prevent Firefox from using them as a trusted root certificate.
    Intermediate certificates that Firefox has stored when visiting websites that show as "Software Security Device" should never has trust bits set.
    Note that it is the responsibility of a server to send all required intermediate certificates to make it possible to build a certificate chain that ends with a built-in root certificate.

  • HT1766 I purchased an iPad air and chose a backup from my iPhone 5s.  The only issue is only 30 of my photos downloaded to my iPad and none of the music.  How can I get all items on the iPad?

    I purchased an iPad air and chose a backup from my iPhone 5s.  The only issue is only 30 of my photos downloaded to my iPad and none of the music.  How can I get all items on the iPad?

    you are using I tunes as the middle man for this back up, right?
    When you plug in the pad to i tunes, give it a unique name, like my pad.  I tune may be thinking it is talking to your phone.  It will keep track of what you what on each device.  Then plug your phone back in, and make sure your photos are uploaded to the computer - in i photo if you are using a mac, or in whatever photo program you are using on a windows device.  You also want to make sure you have uploaded to the computer all of your music.
    Once you get all that stuff there, plug the pad back in, and go through each of the tabs - selecting the music, photos etal that you want on the pad, then resync.

  • How can I kill a thread.

    I have read the many threads about killing a thread but they dont answer the question I need to know.
    In class#1 I have the following snipet of code:
    for (int i=0; i < docs.size(); i++)
        try {
            boolean blncompleted = false;
         Map object = null;
            OntologyCreatorThread  ontThread = new OntologyCreatorThread ();
         ontThread.start();
         ontThread.join(15000); // Allow thread to process for up to 15 seconds.
         // If thread is still running, kill the thread.  I dont care about
         // clean up since its only using memory and cpu, no DB is ever touched.
         if (ontThread.getState().toString().equals("RUNNABLE")){
             ontThread.interrupt();
                ontThread.stop();
                // set flag to false
             blncompleted = false;
            else {
                // set flag to false and do a ton of other processing.
             blncompleted = false;
             object = ontThread.getObject();
        catch (Exception Ex){
            Ex.printStackTrace();
    In my thread I have the following:
    public class OntologyCreatorThread extends Thread {
        Map object = null;
        public OntologyCreatorThread(){
        public void run() {
           try {
             // The line below takes forever to run sometimes.
             object = functionCallToApi(stringOfText);
        public Map getObject() {
         return objects;
    If the thread takes to long to run I just want to kill it.
    I have tried interupt and stop and both dont work.  Inside the run method of the thread I call an external API
    which I pass a string of text.  I can not get into that code because its from a Off the shelf product that we dont
    have the code to.  If the call in the run method takes to long I want to just kill this thread in the main class(#1). 
    No matter what I do I cant get the damn thing to stop.
    The line below takes forever to run.
             object = functionCallToApi(stringOfText);
    Putting it in a while loop wont solve this problem because the processing is still taking place in the call to the api.
    Thanks in advanceMessage was edited by:
    Storm897

    Couple of things to consider:
    1. Note that Thread.interrupted() and t.isInterrupted() are very different methods. The former clears the interrupted status so that a subsequent call will return false. The latter does not affect the interrupt status on the thread.
    2. If your "atomic step one" catches an Exception, then you might be swallowing an InterruptedException. Basically the rule when a Thread is interrupted is that if it is in a blocking call, an InterruptedException is thrown. Otherwise, isInterrupted is set to true. So if you have blocking (I/O) calls in "atomic step one" and you're catching Exception, then it might be that the InterruptedException goes completely unnoticed.
    3. If "atomic step one" takes a long time and you really want to abort the thread instantly, then you need some kind of method for doing so--you need to program in safe "stopping points". For example:
    public class Helper implements Runnable {
       private boolean _continue = true;
       public void cancel() {
          _continue = false;
       public void run() {
          _continue = true;
          try {
             // Do something until in safe/stable state
             if(!_continue) return;
             // Do something until in safe/stable state
             if(!_continue) return;
             while(_continue) {
                 // process single record in large data set
                 // Safe to stop at the end of each loop
             if(!_continue) return;
             // Do something else . . . etc.
          } catch(InterruptedException ie) {
             _continue = false; // Unnecessary, but here for illustration
    }Casual programmers often don't care whether the thread stops safely or not, but it really is important especially if you are in the middle of some kind of transaction. That's why destroy(), cancel() et al are deprecated.

  • I have more than 60 apps on my iphone but only 30 showing on my itunes sync library. How can I upload all apps to the sync library?

    When I try to sync my iphone I get this message that there are apps in the iphone that are not in the library.  It seems that if I sync I will loose those.  How can I make sure that all apps that I have downloaded on iphone are also in the itunes library.

    From iTunes, File > Transfer Purchases.

  • How can I replace ALL Contacts on the iPhone with my MobileMe Contacts?

    I have removed all duplicates in AddressBook on my various Macs and have uploaded the master copy to MobileMe. I would now like to replace all Contacts on my iPhone with that MobileMe master.
    I have followed the steps in the KB article for syncing the iPhone but when I get to the step of turning on the iPhone Settings for the Contacts it looks like the sync wants to merge the contacts. Of course, I do not want to "merge" since that will reintroduce all those duplicates.
    I suppose I could manually delete each of the the hundreds of contacts that are on my phone until it is empty ... and then turn on the iPhone setting for Contacts. That way it will have no option other than "add." But surely there is a more efficient way.
    (FWIW, when I turned OFF the setting for the Calendar it did empty the iPhone's calendar, which is what I wanted. But it didn't do that for the Contacts -- I turned that setting off but I was not asked if I wanted to keep or toss the Contacts. They are all still on the phone.)
    This is an OG iPhone, if that matters.

    Matthew Smith wrote:
    ... The only way I can think of doing it otherwise is possibly by syncing via iTunes via another Mac OS X user account where the address book is empty and then deleting them there and resyncing. ...
    Brilliant! That worked like a charm.
    I created a new User Account on one of my Macs and logged into it. I connected my iPhone to its iTunes and checked my iPhone's Sync Contacts option in iTunes. Since that account's address book was basically empty (two dummy contacts, one for Apple and one for this new user), I ended up with only those two Contacts on the phone. Then, going back to my real User account (which does not have syncing turned on in iTunes) the phone synced nicely with the MobileMe account and populated the phone with all the MobileMe contacts and groups.

  • How can I make all my clips the same size

    Right now I have them in the time line and have used for all of them the option scale to frame size, yet some get full screen size and some don't, I want them all the same size, what can I do?
    Greetings

    Select the clip in the Timeline, open the Effect Controls panel, use Scale to increase or decrease the size of the image.
    Peter Garaway
    Adobe
    Premiere Pro

  • How can I play all albums of a same genre in shuffle mode?

    Since I upgraded my iPhone 5 to iOs 7, I can't play all my albums of a same genre in shuffle mode like I used to do with iOs 6.

    The Touch will only play Albums in the correct track order when you select an album, but then it will only play that one album.
    If you want to play multiple Albums in their correct track order, your options are to either:
    1- Make a playlist in iTunes that is sorted by Album (or Album by Artist), sync the playlist to the Touch, and play the playlist with Shuffle turned OFF, or
    2- Make an On The Go playlist on the Touch by adding one Album at a time and play it with Shuffle turned OFF, or
    3- Look for the free app called "Album Mixer" which gives you the "Album Shuffle" capability found on other iPods -- i.e. the playback is by Album in normal track order, then when the Album completes it will jump to track #1 of a randomly-selected Album and play that one in track order.

  • How can i move ALL of my Iphoto/aperture pictures from the internal hd to a external hd at one session?  just need to how to do this. (I know this is a long process; just looking for a faster method).

    looking for a way other than post and click. 

    I'm not at all sure what you mean by "post and click", but if you wish to move your entire iPhoto Library, then follow these steps:
    http://support.apple.com/kb/PH2506
    As far as I know, you can set up Aperture to access its library on an external drive; I tried to find some info for you and found this support site for it - you might want to check it out. Also, you might want to check the manual on how to move the library.
    http://www.apple.com/support/aperture/

Maybe you are looking for