Ending a Thread Loop

Hello i'm trying to finish this program but the problem is it doesn't end at 100. I'm trying to make the program end when the first animal reach 100 in the position instance, but it continues to finish the thread. How can i end the program when the first thread reaches 100?
import java.util.Random;
    public class Animal extends Thread implements Runnable{
      private String name;
      private int position;
      private int speed;
      private int restMax;
      public static boolean winner = false;
      Random random = new Random();
       public Animal (String name, int position, int speed,int restMax){
         this.name = name;
         this.position = position;
         this.speed = speed;
         this.restMax = restMax;
       public void run(){
         try{
            while(winner == false){
               if (position < 100){
                  Thread.sleep(random.nextInt(restMax));
                  position += speed ;
                  System.out.println(name+" is in "+ position+" position ");
                  if (position == 100){
                     winner = true;
             catch(InterruptedException e){
       public static void main(String[] args){
         Animal rabbit = new Animal("trix", 0, 5, 150);
         Animal turtle = new Animal("maury",0, 3, 10);
         rabbit.start();
         turtle.start();
   }

try the code below
import java.util.Random;
public class Animal extends Thread implements Runnable
     private String name;
     private static int position;
     private int speed;
     private int restMax;
     public static boolean winner = false;
     Random random = new Random();
     public Animal (String name, int position, int speed,int restMax)
          this.name = name;
          this.position = position;
          this.speed = speed;
          this.restMax = restMax;
     public void run()
          try
               while(winner == false)
                    if ((position+speed) > 99)
                              winner = true;
                              System.exit(0);
                    if (position < 100)
                         Thread.sleep(random.nextInt(restMax));
                         position += speed ;
                         System.out.println(name+" is in "+ position+" position ");
          catch(InterruptedException e)
     public static void main(String[] args)
          Animal rabbit = new Animal("trix", 0, 5, 150);
          Animal turtle = new Animal("maury",0, 3, 10);
          Animal ant = new Animal("anto",0, 7, 50);
          rabbit.start();
          turtle.start();
          ant.start();

Similar Messages

  • Crackle at the end of a loop

    There is always a quiet but annoying crackle at the end of my loops when I record from a real instrument.
    What can I do?

    I haven't noticed a "crackle" but I have noticed that sometimes when I create a loop it ends up with its tail chopped off. And when this happens, these loops have the missing tail added to the front of the loop.
    It's really annoying and I haven't found any way to reproduce the problem consistently (otherwise, I'd file a bug).
    All of my loops are the spoken voice, so it's easy to tell when the first bit of audio is actually from the last bit of speech from the end of the loops.
    This happened on GB '08, both before and after the latest set of patches (circa Sept '07). I'm using a PowerMac G5 dual 2GHz, for what it's worth.

  • Never ending automatic repair loop

    I'm working on a client's HP ENVY TouchSmart 4-1215dx Ultrabook that is stuck in a never-ending automatic repair loop. I have done a system diag...all passed . Tried multiple ways to get into BIOS to do a repair from a USB stick made from another OS 8....but can't get into BIOS to change the boot. Tried F11 to do factoy resest....just puts me back into the loop.  I have a feeling my client downloaded a bad 8.1. Considering pulling the HDD and using my desktop to at least try and save her personal data....Please help!

    Kris_ClearFIxPC wrote:
    I'm working on a client's HP ENVY TouchSmart 4-1215dx Ultrabook that is stuck in a never-ending automatic repair loop. I have done a system diag...all passed . Tried multiple ways to get into BIOS to do a repair from a USB stick made from another OS 8....but can't get into BIOS to change the boot. Tried F11 to do factoy resest....just puts me back into the loop.  I have a feeling my client downloaded a bad 8.1. Considering pulling the HDD and using my desktop to at least try and save her personal data....Please help!
    That would be the best thing to first do and then use the recovery media of which you will now have to order since the O/S seems corrupted beyond repairs. This way you can be sure the recovery media will restore it back to factory install and hopefully they will not do this again til they will consult first before upgrading the O/S.
    I am a Volunteer to help others on here-not a HP employee.
    Replies aren't online 24/7 because of Time Zone differences.
    Remember in this Day and Age of Computing the Internet is Knowledge at your fingertips if you choose understand it. -2015-

  • Trouble ending a thread in InDesign CS6?

    I am having trouble ending a thread in a long document with separate sections. Using InDesign CS6 on Mac running OSX 10.6.8.  I checked Online Help and it says to double click either the In or Out box. This doesn't work, just loads the Select tool with text. I tried holding down Command, Option, and shift alternately and in combination while doing it, didn't alter the result. Any advice please?

    fijiboy67 wrote:
    No, sorry, clicking the outbox is exactly what I have been doing, but it just loads the select tool with text.
    Yes.
    If I then click in the same box it merely superimposes text on that page.
    No. You must click INSIDE the same FRAME (don't try to double-click or click in the outport again). This will break the link to the following frames and leave your last frame overset if there was text in those following frames.
    If I just stop linking and start afresh on a new page, it shows up as an error on the Pre-flight panel.
    What error?
    If you want to break apart a story into several different stories you need to cut the overset text from the first story and paste it into a new frame (or the still linked-to-one-another frames that you unlinked from the story in the earlier step.
    You can use the DivideStory.jsx script to automate the process:
    //DESCRIPTION: Splits story at the selected text frame.
    // The selected frame becomes the first of the new story.
    // Note that the behavior when an overset last frame is selected
    // is different from that of the break-out text frame script.
    // This script moves the overset text to the second story while
    // breaking out the last frame leaves the overset text attached to the first story.
    if ((app.documents.length != 0) && (app.selection.length != 0)) {
         var myFrame = app.selection[0];
         if (myFrame.constructor.name != "TextFrame") {
              errorExit('Please select a text frame');
         var myStory = myFrame.parentStory;
         var mySplit = myFrame.textFrameIndex;
         var myTot = myStory.textFrames.length;
         // Because of the possibility of tables, we must always work from the back
         var myStart = myTot - 1;
         var myEnd = mySplit;
         // Nothing to do if user has selected first frame.
         if (myEnd != 0) {
              if (myStart > myEnd) {
                   var myPrevFrame = splitMe(myStory.textFrames[myStart]);
                   myStart--;
                   for (var i = myStart; i> myEnd; i--) {
                        var myNewFrame = splitMe(myStory.textFrames[i]);
                        myPrevFrame.previousTextFrame = myNewFrame;
                        myPrevFrame = myNewFrame;
              // Now we deal with the last frame
              myFrame = myStory.textFrames[myEnd]
              try {
                   myIndex = myFrame.characters[0].index;
                   stEnd = myStory.length - 1;
                   myText = myStory.texts[0].characters.itemByRange(myIndex,stEnd);
              } catch (e) { } // Ignore; happens if last character is a table or frames are empty.
              myNewFrame = myFrame.duplicate();
              try{myText.remove();}catch(e){} //ignore empty frame
              myFrame.remove();
              try{myPrevFrame.previousTextFrame = myNewFrame;}catch(e){} //fails if one frame only
              //Finally, if, and only if, the split is mid-table, myStory is now overset
              if (myStory.textFrames[-1].overflows) {
                   myTable = myStory.characters[-1].tables[0];
                   myNewTable = myNewFrame.parentStory.characters[0].tables[0];
                   myRowCount = myNewTable.rows.length;
                   myTable.rows.itemByRange(0 - myRowCount,-1).remove();
    } else {
         errorExit();
    // +++++++ Functions Start Here +++++++++++++++++++++++
    function splitMe(myFrame) {
         myDupeFrame = myFrame.duplicate();
         while(myDupeFrame.contents.length > 0) {
              myDupeFrame.texts[0].remove();
         myFrame.remove();
         return myDupeFrame;
    function errorExit(message) {
         if (arguments.length > 0) {
              if (app.version != 3) { beep() } // CS2 includes beep() function.
              alert(message);
         exit(); // CS exits with a beep; CS2 exits silently.
    // +++++++ Script Ends Here ++++++++++++++++++++++++++
    I believe this was written by Dave Saunders. I have it in a "Version 4.0 Scripts" subfolder in my Scripts Panel folder because it is very old and may not run correctly without being in such a subfolder. The subfolder name is case-sensitive, but should not include the quotes.

  • Ending a thread that is locked ?

    Hi all,
    I know there's no built in "kill thread" in j2me, or so I've read over and over. I use multiple threads with the RUN() loop that checks for a "die" variable trigger.
    The problem I have is when a thread which is doing a socket stream input read() and is locked, waiting for a response. I want to end it quickly rather than letting it time out.
    What I have is a method in the main thread and in that method it declares a local variable of a runnable IO class and starts up that IO class/thread. If the IO goes into a read and does not come back right away, and if, through some other information, the method determines there is no need to wait anymore for a reponse from the IO thread, the main method exits. Since the IO thread is locked on the read(), the main method cannot set the "die" boolean to TRUE in the run loop of the IO thread.
    Hence, if the main method exits, then the local var, which is the runable class/thread, goes out of scope. I presume then that the thread is killed by the JVM or GC ? This seems a very dirty approach. Since the thread var is out of scope, will proper GC occur for all resources in the IO thread or would it create memory leaks?
    Thanks for any input and suggests on alternate ways to get the IO thread immediate attention.
    Cheers,
    Eric

    The usable number of threads is actualy very dependant of the device you use. The documentation of the device I'm currently working on tells me that theading actually performs better in a lot of cases. And indeed it does. Furthermore, if you use TimerTasks, having more threads is no problem, since, they won't run most of the time.

  • Real Instruments play beyond end of repeated loop

    I've tried every google-fu trick I could think of to see if anyone else has had this problem.
    I record a real instrument (say an electric guitar riff). I drag/repeat/loop it 3 or 4 times. It plays properly.
    Then at some point I select it, and move it left or right.
    The part starts at the right time, but will repeat an extra time beyond the visible onscreen loop. Once this glitch occurs, neither resaving, shrinking/re-repeating, moving it around and then back to where I want it make the track end when it's supposed to.
    The only way I've found around it, is to end the repeat early and let the erroneous repeat play out, or just end the repeat entirely, and use cut'n'paste instead.
    This happens to me *all the time*... anyone else seen this or have a resolution?

    Thanks for the suggestions. I can't remember deleting any tracks... however, how would i check for "hidden" tracks?
    The funny thing is i can hear the effect returns for the real instrument tracks...tracks that are heavily reverbed i can hear a faint echo of the track. and like i mentioned the drum loop and software piano still play fine.
    And, I also see monitor activity in the real instrument tracks when i play the song. Everything looks normal, but of course, the sound isn't there.
    Thanks again for your help!
    Message was edited by: Ike the Longshoreman
    P.S. I just tried Unsolo all tracks and Unmute all tracks... still the same problem.

  • Inserting a pause at the end of a loop in a film clip...

    Hi,
    I just scanned in 16 frames from old 16 mm film and created a short clip in .swf, by default the clip is looping.
    I want it to loop, but all I want to do is place a 5 second pause at the end of the short 1 second clip before it starts up again.  How would I do that?  Or is there a simple tutorial on this?
    I am using CS4 Flash Professional.
    Thanks.

    OK thanks much,
    So to do that, do i begin by highlighting the last frame (the last frame of the movie itself - actual film image) on the timeline, and go to main menu and select Insert>Timeline>Keyframe?  Then insert stop(); on the last frame via the actionscript panel?
    Then highlight the first frame and insert the setTtimeout() and  play() onto the first frame?
    I inserted the stop() command on the last frame and the clip now stops...
    I tried adding this script on the last frame and clip stops but does not repeat after 5 seconds...
    stop()
    setTimeout(5)
    play();

  • How to make a Thread loop?

    Hi, I was wondering how to make a thread start over again from the beginning once it finishes, if it hasn't been stopped already.

    package src.Utility;
    public class ThreaTest extends Thread{
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              ThreaTest threaTest= new ThreaTest();
              while(true){
                   try{
                   if (!threaTest.isAlive()){
                        threaTest= new ThreaTest();
                        threaTest.start();
                   }//else{
                        //System.out.println("");
                   }catch (Exception e) {
                        e.printStackTrace();
         public void run(){
              System.out.println("-----11---------");
    }try the above code and then tell me if this loop works for you???

  • Trouble with DAQmxReadDigital Timeout (200284) when used in a threaded loop

    Hi,
    I'm using a NI6537 for fast Digital Acquisition. The board is installed on a NIPXIe-1062 crate controlled by a NI PXIe-8130 controller, where the software is running. I'm reading all the 32 lines as a single channel, at 50MS/s, and the clock is the one provided by the board itself. I put the timeout as infinite, but I also tried various other settings. As I'm reading a finite samples bunch of 524288 samples, at 50 MS/s, a timeout of 1 second should be by far sufficient.
    As far as I put the DAQmxReadDigitalU32(...) call in a simple loop I have no troubles, everything working fine.
    for (...) {
       DAQmxReadDigitalU32(...);
    } // That loop works perfectly
    while, if a have a loop inside a multi-thread process, or simply I give the system some freedom inside the loop, sometimes I get the timeout error. Note that the time cost of the Sleep() function is just of some millisecond, so there is no reason for the call to timeout.
    for (...) {
       DAQmxReadDigitalU32(...);
       Sleep(1); // To release system resources...
    }// That loop stops erratically
    With the last code, I can also see that actually the board did not complete the reading, i.e. is returning less samples than what requested. It seems to me that someting is stopping the acquisition, but I'm not able to figure what. The same happens even in LabView, using the VI read: sometimes the read randomly generates a timeout error and stops, even if LabView is the only running application.
    Could you point me what I'm doing wrong?
    Thanks, Piero.
    DAQmxReadDigitalU32

    Duplicate Post
    ColeR
    Field Engineer

  • Ending an Endless Loop

              while (! source.nextTokenIs('}'))
                   dec = new ClassMemberDeclaration();         
                   dec.compile(source);
              }basically this question is regarding the above loop. This is a while loop that is looking for curly braces (i.e. } ) . But if there are no curly braces of that kind in the file that i am reading then this while loop becomes an endless loop. hence is there any way of timing this method, and after certain time (say 20 seconds the while loop is aborted and a message is displayed saying that the closing curly brace was not found????
    please ignore the body of the method as it was just put there so that you could understand what i was on about.
    please do reply, thank you
    best regards
    alpha

    Endless loop? See this thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=531136&tstart=0&trange=15

  • Input thread - loop question

    Sorry for all the annoying questions. Just one more answered would be great, I know the problem in this code is my Input class only reads and sends one line to the server and as it isn't in a loop thethread terminates immediately, after one line leaving only the thread that's reading data from the server. I've tried a few loops but nothing seems to work. Can anyone point out what kind of while loop and where i can put it in.
    import java.net.*;
    import java.io.*;
    class Input extends Thread
    private PrintWriter toServer;
    private BufferedReader keyBoard;
    private Socket socket;
    public Input(Socket sock)
    socket = sock;
    public void run()
    keyBoard = new BufferedReader(
    new InputStreamReader (System.in));
    try {
    toServer = new PrintWriter(
    new OutputStreamWriter(
    socket.getOutputStream()),true);
    catch(Exception e) {
    String command ="";
    try {
    command = keyBoard.readLine();
    catch (IOException e) {
    toServer.println(command);
    }

    try
    try {
         command = keyBoard.readLine();
         while (command != null) {
               toServer.println(command);
              command = keyBoard.readLine();
    } catch (IOException e) {
         e.printSTackTrace();
    }

  • Separate UI thread/loop/??

    I am working on a LabView program which does a lot of data acquisition.  The program is setup as a state machine and some sub-VI's take 10 or more seconds to complete (FFTs, data acquisition, etc..).  I have tried everything that I can think of to make the user interface usable during this time. However, if a user clicks on a button, it takes 10 or more seconds for the sub-VI to finish and to acknowledge the button.  I have tried putting things in events blocks, separate while loops, etc...  Is there anything that I can do to make the UI more responsive?
    Thanks!
    Drew

    First, make sure the code that handles the user interface is in a separate loop, preferably with an event structure.  It can pass messages into the state machine loop by way of queues.
    For the subVI's, it depends on what they are doing and what you want them to do at certain button presses.  Do you want a subVI to end early?  You could also pass in a reference to a queue or notifier into the subVI.  Have the subVI check for any messages during its looping process such as a command to end early.

  • How do I increment a variable at the end of a loop to run it through the loop again?

    I'm new to LabVIEW programming and I'm trying to write a small program that just receives a lower and upper limit, and whether the user wants to increment or decrement the number. I can't figure out how to increment the number after the simple calculations have been done and to run through the loop again with the incremented number. Right now I'm using a while loop inside of a case structure where true decrements and false increments.

    Here are a few possibilities.
    Message Edited by altenbach on 12-05-2008 03:25 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    fractionaIncrement.png ‏8 KB

  • End a while loop

    For this example:
    int x = 1, y = 2;
    while (x == 1)
    if (y = 2)
    y -= 1;
    if (y = 1)
    y -= 1;
    }Is there a line I can put in the first if statement block to make the loop and and repeat? I'm having a problem with if statements that after one is true, it makes one following it also true. I only want one to be executed, so if I could make the while loop repeat after an if statement is true, I could fix that problem

    I'm having a problem with if statements that after one is true, it makes one following it also true. I only want one to be executedOr perhaps "else if"
    while(foo) {
      if(cond1) {
        cond2 = true;
      } else if(cond2) {
        cond1 = true;
    }

  • Please tell me about the start and end of a loop at main

    part of the table?
    I have put a table into the smartform page and I do not know how to use loop and program lines.
    For what purpose should I use these?
    Any contributions will be rewarded.
    Thanks.Deniz.

    Loop and endloop in smartform - if you want to print multiple data for each header ,then we need to use..
    one example : i have sales order - order may contains more than one item..if you want to print multiple items then we need to go for loop endloop.
    Program lines - without effecting program - we can change the code within smartform( I mean we can pass the values and get the values based on condition )
    i am getting material number from program and i am printing here,later on customer is looking for material description,then you can write simple code within samrtform by using program lines.

Maybe you are looking for

  • "Generic" material master in MRP run

    Hi Our business users want to use MRP to manage the stock of materials such as circuit breakers. There are however many manufacturers/types and while a certain specification is required, they would be happy to purchase from a variety of suppliers who

  • Why are my Illustrator Cs6 PDFs missing / displaying colours incorrectly?

    I recently upgraded to Cs6, and since doing so have noticed the PDFs i'm ouputting are displaying terrible on both mine and clients' Macs alike. When viewed with Adobe Acrobat they are fine, but if I use any Mac native applications like Preview they

  • Remote website question

    I have a website through 1 and 1 Internet. I have used Frontpage forever as it's very easy to edit my page. They are discontinuing support of this format. I would like to be able to edit my site without having to load all the info on my website to a

  • Re-order point...

    Hi, What is different between manual and automatic re order point..? and which scenerios we can use manual and automatic re order point..? Thnaks & Regards, Senthil S

  • Safari not opening many webpages - just get 'blank' webpages

    I added "index.html" at the end of the URL's and it worked but I'd like to know why I have to do this. BTW, I couldn't log onto this site with Safari and finally had to use FireFox. I know about emptying caches, deleting cookies but I shouldn't have