Solved

Breaking out of an Infinite loop if user clicks a button

Posted on 1997-06-13
3
316 Views
Last Modified: 2012-05-04
Hello;
        Here's my problem. I need to keep on looping through some calculations till the answer is found. While it's doing this I would like to have a pause button so that the user can change the variables in real time. The problem is that the loop will continue till the end. If I use the action() method to capture the mouse click (such as a pause button) the results will only be shown when the calculations are done.

    Any idea of how to temporally stop the loop? I tried make the loop so that it looks like this:
            while(running == true)

    and set the running variable false when the user hit's pause but this is done when the answer is found.

     I also thought of creating another thread for the buttons and pausing the default thread that to allow the other thread a chance.  This brought up some questions also:

        If I declare a thread such as (Thread my_thread null) is this the default thread that Java uses or is there another thread created every time a program runs? If this isn't the main thread does anyone know how to pause it and give control to another thread that may be waiting around?

     Finally, someone suggested to me that I should use the
Thread.yield() in my loop to allow the action method a chance to do it's work but the loop continue's on till it's all done.


Louis Calisi
louiscal@bu.edu
0
Comment
Question by:louiscal
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 6

Accepted Solution

by:
jpk041897 earned 50 total points
ID: 1221676
To pause the thread try using sleep().

The default thread is actualy the message loop for the app. or thread. You cna hook into it at the begining using main() for apps or init() for threads.

When you instantiate a thread, it represnts a new thread (child process). Now, there is nothing wrong with the yield()idea. The problem is that you are not pausing the threads thats yealding. If both threads have the same priority it will usualy just chug allong as if you hadn't yealded in non premptive schedulers.

To solve this, I would suggest you use Thread's setPriority()method and give the button processing thread a higher priority than the main loop. Higher is diferent on each platform, a diference of 1 is usualy good enough for UNIX, Windows on the other hand usualy requires a difference of several thousands.

The following program can help you test priorities:

public class RunnablePottato implements Runnable{
   public void run(){
      while(true){
         System.out.println(Thread.currentThread().getName());
         Thread.yeald();
      }
   }
}

public class PriorityTester{
   public static void main(String argv[]){
      RunnablePottato aRP = new RunnablePottato();
      Thread t1 = new Thread(aRP, "onePottato);
      Thread t2 = new Thread(aRP, "twoPottato");

      t2.setPriority(t1.getPriority() + 1);
      t1.start();
      t2.start();
   }
}

If you set bot priorities equal, in a non premptive environment like windows, you will only print data from a single thread. If you are running under windows change the priority value from 1 to 1000 or more.
0
 

Author Comment

by:louiscal
ID: 1221677
    That was helpfull but it brought up some new questions. Using Visual Cafe I can only get this program to execute as am application and not an applet. I modified the code that you sent me and this is what it currently looks like (all in one file):


import java.awt.*;
import java.applet.*;

 public class PriorityTester extends Applet implements Runnable
 {  
    public static void main(String argv[])
    {
        System.out.println("hello main");
        RunnablePottato aRP = new RunnablePottato();
        Thread t1 = new Thread(aRP, "onePottato");
        Thread t2 = new Thread(aRP, "twoPottato");

        t2.setPriority(t1.getPriority() + 1);
        t1.start();
        t2.start();
     }
 
    public void run()
    {
   
        while(true)
        {
            System.out.println("hello run");
            System.out.println(Thread.currentThread().getName());
            Thread.yield();

        }
    }
     
 }


   What is the the string arg thing in this program used for?

   When it comes time to write my real program it has these functions: init, run, calculate (does the mathematical operations for the model), handle event, paint and now main.

   Should my new program framework look like this so that the buttons can have higher priority than the calculations:


import ...

public class model extends Applet implements Runnable
{
   global variables

   public static void main(String argv[])
   {
      - handle event() and all the button functions
      - start()
   }

   init()
   
   run()

   calculate()

   repaint()

}


   Or does it matter if the handle event stuff is outside the main? If this is the case then how do you create a thread so that "it is connented" to the buttons.


Thanks alot



Louis Calisi
louiscal@bu.edu
 
0
 
LVL 6

Expert Comment

by:jpk041897
ID: 1221678
First of all, main() is a method that is only valid in the context of an application.:-) In order to get it to run in applet, you can place the code contained in the main() method I sent you and place it either in the init() method, the start() method, or in a separate method that is called by one of these two.

For a good refresher on writting applets see:

http://www.mcp.com/que/et/se_java2e/15javafi.htm

and

http://www.mcp.com/que/et/se_java2e/16javafi.htm

String args[] is used by applications to be able to parse command line arguments. Say you invoke your Java app. as follows:

java copy file1 file2

then, args[0] will contain "file1" and args[1] will contain "file2".

It seems that the code I sent you acomplished to confuse you.

The purpose of the code was to give you a stand alone application that would aid you in determining if your OS has pre emptive or non premtive multitasking (threads). Based on that, you could use the same code to find priority settings that would work well under your plattform. (diferent plattforms work better with diferent settings).

The final reason I sent that block of code is that you can implement the techniques for setting priorities and calling the yield() method in your own code, with something that works as a referance.:-)

Using an application, rather than an applet, is a combination of kindliness and lazyness. An application does not need an HTML file and/or a web server to run, making using it eisier.


Have a look at the material for applets that I have refered to you, then look at:

http://www.inf.uni-hohenheim.de/top/java/tutorial/java/threads/index.html

for good info on threads. When your done reviewing all this info, you'll be prety close to mastering both subjects.

I'll be available to answer any further questions you might have on these subjects by e-mail at:

jkelleghan@usa.net

Feel free to ask away.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

695 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question