How do I set a variable on the main timeline from within a symbol?

Just getting started with Animate and coming to it from Flash, as may be apparent from my question. How do you set a variable to the main timeline from within a symbol?
I have 24 pairs of clickable elements, each in their own symbols, and all 24 of those symbols sit inside another symbol. I want all 24 to be able to set the same global variable when clicked. I can't find that this question is addressed anywhere, which makes me think I may be stuck in a Flash mindset and approaching the task in the wrong way. (There are however MANY discussions of how to address objects at different levels in the hierarchy. That's well covered.)
Relatedly, how do you access a function on the main timeline from within a symbol?
Adobe should consider putting together a support page (or pages) just for folks migrating form Flash. In the materials I've encountered so far there seems to be a studied effort to refrain from mentioning Flash in any way. I imagine there are a lot of people out there like me who have a deep background in Flash coding, but are just getting started with Animate. We don't need help with most of the basic concepts, but we may still have some pretty basic questions about how to accomplish some things in Animate because our Flash knowledge is getting in the way.

Hi Bill,
There are plenty of threads on here about scope, but here's one way to create a global variable:
// code on Stage.compositionReady
sym.myGlobalVar = 1;
Then, anywhere in your project, you can check/set that var like so:
sym.getComposition().getStage().myGlobalVar = 2;
And here's one way to create a global function:
// code on Stage.compositionReady
sym.myGlobalFunction = function(){
          console.log('myGlobalFunction');
Then, anywhere in your project, you can call that function like so:
sym.getComposition().getStage().myGlobalFunction();

Similar Messages

  • How to control the main timeline from within a symbol?

    I have a small world map as a symbol called "verden" and I want the user to click Europe, Asia, or Africa and jump to named labels in the main timeline.
    http://www.dagbladet.no/grafikk/neshorn/neshorn.html
    On the main timeline a have the label "intro" with a Stop action and the label "europa". At label "europa" I have a symbol also called "europa" which has a display of None at label "intro" and On at the label "europa".
    The animation never goes to label "europa"
    I have this code on europa in the symbol "verden" :
    // insert code for mouse click here
    sym.getComposition().getStage().getSymbol("europa").play("europa");
    The files are on Dropbox here
    Update, now it works:
    sym.getComposition().getStage().play("europa");

    Hi Bill,
    There are plenty of threads on here about scope, but here's one way to create a global variable:
    // code on Stage.compositionReady
    sym.myGlobalVar = 1;
    Then, anywhere in your project, you can check/set that var like so:
    sym.getComposition().getStage().myGlobalVar = 2;
    And here's one way to create a global function:
    // code on Stage.compositionReady
    sym.myGlobalFunction = function(){
              console.log('myGlobalFunction');
    Then, anywhere in your project, you can call that function like so:
    sym.getComposition().getStage().myGlobalFunction();

  • How do I recerence Movie Clips on the Main Timeline from inside a class?

    Hey everyone, this might be a stupid question but I thought
    I'd ask cause it's making me nuts. I'm all of 2 days into AS3
    (coming from not using Flash at all in YEARS) so feel free to
    consider me ignorant. I do have plenty of application development
    experience in other areas though.
    I can't seem to create a class that can reference an instance
    of a movie clip on my main timeline. I'd post code of what I've
    tried but I've gone through so many desperate edits & wild
    guesses that it was just garbled junk before I deleted it all.
    Basically here's how I figured Flash could work, though maybe
    it doesn't work this way at all.
    I'm assuming that with AS 3 being so big on being a true
    object oriented environment, I wouldn't need to mix my code and
    interface together. Preferably I'd be using the Flash authoring
    tools just to design my interface. Create a button... place it
    somewhere... give it an instance name. Roughly the equivilant of
    Apple's InterfaceBuilder for those of you that might be familiar
    with Cocoa development. I can see maybe having to put a few lines
    of ActionScript onto frame 1 (though really I'm hoping Flash would
    have a better method of kicking off the application at this point
    that using code tied to frames) to load my classes & such, but
    after that I'd like all of my code to be held in external class
    files.
    So maybe I've got:
    Interface.fla - My interface
    Button_1
    Button_2
    TextField_1
    Main.as - My main controller class using to handle all of my
    applications behavior
    SomeClass.as - Some helper Class
    SomeOtherClass.as - Some helper Class
    Main.as would have instructions in its initialization method
    to go ahead & attach events to buttons & initialize
    anything else that needs to happen when the application starts.
    From there on it would all be objects communicating back &
    forth. Button_1 would get clicked with would fire
    Main.someMethod(). Main.someMethod() would then do it's thing and
    set the value of TextField_1. All very clean & code is very
    separated from interface.
    Unfortunately I can't for the life of me figure out how AS3
    classes reference each other like that. There doesn't seem to be
    any kind of a global 'root' or '_root' I can use to locate any
    movie clips on the stage. I've searched the help & the web for
    any kind of simple tutorial but to no avail. My job has tasked me
    with building a flash app for a project but I'd really rather not
    have a tone of ActionScript just shoved into frame 1. That just
    seems... ugh! (::shudder::)
    Can someone maybe point me in the right direction here? I'm
    really willing to do my homework but I can't seem to locate the
    info I need to get started. Also, is there an ActionScript IRC
    channel or something maybe?
    Thanks,
    Cliff

    I worked with the problem last night and the solution I
    started coming to involved creating my own custom document class
    based off which extends MovieClip. My thought is that way I have
    access to the initialization routine of the timeline itself and
    that all of the elements on the main timeline should be
    "properties" of my custom class.
    Is this correct? Is there a down side to doing this & if
    so what is it & why?
    Also, just for my reference, the last time I did anything
    with ActionScript I think I was using '_root' to target the main
    timeline. WHat are the global variable names in AS 3? Is it just
    'root' & 'stage' or 'Root' & 'Stage' or what?

  • Controlling a Movie Clip on the Main Timeline from a loaded SWF?

    Is it possible to control a MovieClip on the main timelne from another loaded clip?
    I see posts that control loaded clips, but most are all from the loader in the main timeline.  I have a moviclip on the main timeline that I want to make visible or invisible depending on what keyframe is playing in another loaded swf.
    If I try to call the movieClip from the loaded SWF I get "error #1119.  Access of possibly undefined property...." because it doesn't exist in the loaded SWF, just the main timeline. 
    The old AS2 way just used "_root".  Since "_root" doesn't exist any more, how do you control items on the main TimeLine from a loaded SWF?

    I am not clear what you mean because you are saying you are trying to target a movieclip that does not exist where you are trying to target it.
    Try using a trace to see what you are targeting when you you target the MovieClip(parent.parent)....
    trace(MovieClip(parent.parent));
    The other approach I mentioned earlier is the more OOP-correct approach if you would rather try that way.  Here's a rough outline of it...
    AS3 - Dispatch Event
    http://forums.adobe.com/thread/470135?tstart=120
    Example:
    Add something to trigger the event in the child (your loaded swf):
    dispatchEvent(new Event("eventTriggered")); (
    if dispatchEvent problem, see: http://www.kirupa.com/forum/showthread.php?p=1899603#post1899603)
    In your loading/parent swf, listen for the complete event on the Loader.contentLoaderInfo.  In the complete event handler, add a listener for the event on the loaded swf.
    // event handler triggered when external swf is loaded
    function loaderCompleteHandler(event:Event) {
        MovieClip(event.currentTarget.content).addEventListener("eventTriggered", eventHandler);
    function eventHandler(event:Event):void {
        trace("event dispatched in loaded swf");
       // this is where your main file can set the visible property of your movieclip

  • Remove child on the root timeline from within a movieclip

    Hi
    How do I remove a child from the root timeline from within a separate movieclip?
    I've tried
    MovieClip(parent).removeChild(mc1);
    But I get this error
    1120: Access of undefined property mc1.
    I could write a function in the root timeline that just removes child and then run that from within the movieclip but is there a better way?
    Thanks in advance.

    Thanks for replying.
    I asked on Kirupa but I couldn't access the site so I asked here.
    I guy answered with this
    MovieClip(parent).removeChild(MovieClip(parent).getChildByName("mc1"));
    It works fine, is this the best way to do it?
    Not sure if I understand what you meant?
    Just to be clear I have to movie clips on the stage mc1 and mc2 and i want to remove mc1 from within mc2's timeline.
    Thanks again

  • Toolkit for CreateJS: How to control the main timeline from outside the canvas.

    Hey Everyone,
    I'm currently trying to do something simple, but my animation breaks whenever I attempt to change my code. I have created a basic animation in Flash where an object moves from the left side of the canvas, to the right, and then loops from the last frame to the first frame. Nothing else. The animation is simply put on the main timeline. I exported the animation with Toolkit for CreateJS through Flash's extension and the animation runs as it should. I am trying to start and stop (restarting from the first frame) the animation with mouse over and mouse off events. I want the events to fire when moused over/off a div OUTSIDE the animation's canvas tag. Is this possible with CreateJS? I'm trying to figure out how to control the main timeline without being inside the canvas tag.
    Example HTML:
    http://www.thephotoncore.com/testing/example_test.html
    Example Code:
    <section id="container">
      <canvas id="canvas" width="550" height="400" style="background-color:#cccccc"></canvas>
      <section id="animation_control">
        <p>Roll over to start and stop animation.</p>
      </section>
    </section>
    Thanks again for the help!
    -DJ

    Hi DjPhantasy5,
    All movieclips on the stage are children of the stage,
    So on the "mouseover" all movieclips on the stage could be stopped with stop and on the "mouseout" all children could be restarted with gotoAndPlay like this:
    function Stop()
              if (stage && stage.children)
                        var i, l = stage.children.length;
                        for (i = 0; i < l; i++)
                                  var child = stage.children[i];
                                  if ("stop" in child)
                                            child.stop();
    function Restart()
              if (stage && stage.children)
                        var i, l = stage.children.length;
                        for (i = 0; i < l; i++)
                                  var child = stage.children[i];
                                  if ("gotoAndPlay" in child)
                                            child.gotoAndPlay(0);
    See http://www.liauw.nl/forums/adobe/djfantasy5/index.html
    But it is also possible to expose "ball1", for example, by adding it to the document.
    This can be done by adding code to "ball1" like so:
    /* js
    document.ball1 = this;
    Then the stopping of the animation would look like:
    function Stop()
         if ("ball1" in document)
              document.ball1.stop();
    etc.
    Have fun!
    Ronald

  • Referencing the main timeline from elsewhere

    From inside a movie clip (button) which is inside a display
    object (buttonSet), I want to gotoAndPlay a specific frame on the
    main timeline. I've tried stage.gotoAndPlay(thisFrame). I got
    closer with gotoAndPlay(stage.thisFrame). I still have something
    wrong.
    I have about 15 frames on the main timeline. Each frame
    contains a myriad of objects all doing different things. Most
    importantly they transition from frame to frame based on the
    current frame (last button clicked) and the next frame (the newly
    clicked button).
    Example: the last button that was clicked was button #4, the
    button I have just clicked is button #2. Based on this knowledge, I
    want the main timeline to gotoAndPlay frame #6.
    Thanks for the aid. :)

    the flash compiler (in strict mode) often has trouble
    "remembering" the class-type of objects/variables. "typing" those
    objects explicitly helps the compiler to overcome erroneous error
    messages.

  • Load a MC on the main timeline from a MC.     AS3

    I have a movie clip (mc_menu) on that is on the main timeline.
    This movie clip has buttons that I want to use to display other movie clips on the main (parent) timeline.

    Start here:
    http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9 b90204-7e4e.html

  • How do I set a variable via the web serviices?

    (I am new to Business Objects.)
    I would like to know how, using web services, I can set a variable in a parameterized ad hoc query.
    Let's say I have obtained a Session from a Connection - what class/method must I call to do this?
    Not sure of the difference between prompt/variable in this regard.
    A code snippet would be much appreciated. I have looked at the Javadocs but they're rather minimal.
    Thanks in advance.

    You are problably looking at using the query web service which is meant for developers, NOT the Query as a Web Service.
    http://devlibrary.businessobjects.com/BusinessObjectsXIR2SP2/en/en/WS_SDK/wssdk_consumer/doc/wssdk_dg/DevelopingConsumerWebApps76.html#1120164
    Francois Imberton

  • How to target main timeline from within 3 mcs in a slidemenu?

    Hello there,
    I am trying to modify a slidemenu script but don't really
    know how to accomplish it. I have a series of buttons within three
    mcs. (this is necessary for the sliding script to work). In the
    original script, the button name is targeted to a label with the
    same name in a new scene.
    The code on the button is:
    on (release) {
    gotoAndStop("/:" add eval("..:text"));
    // THIS goes to the FRAME with the name of the button you
    just clicked on.
    The MC code is:
    // tmi=total menu items
    // dup=new movie duplicates
    // butn=original movie button
    // FIX original Button:
    butn:text = /:Menu0;
    while (Number(n)<Number((/:tmi*2)-1)) {
    n = Number(n)+1;
    dup = "butn" add n;
    duplicateMovieClip("butn", dup, n);
    setProperty(dup, _x, Number(getProperty(dup,
    _x))+Number(n*getProperty(dup, _width)));
    setProperty(dup add "/b", _x, getProperty (dup add "/b", _x)
    + (1));
    set(dup add ":n", n);
    // assign button name from variables
    if (Number(n)<Number(..:tmi)) {
    set(dup add ":text", eval("/:Menu" add n));
    } else {
    set(dup add ":text", eval("/:Menu" add (n-/:tmi)));
    The problem I am having is that I don't want to go to a new
    scene ( because I am only loading photos) but would like to target
    a label on the main menu. I have tried many ways including (my
    label is named "one"):
    on (release) {
    _root.gotoAndStop("Main" "one");
    on (release) {
    _root.gotoAndStop("one");
    on (release) {
    gotoAndStop("Main" "one");
    on (release) {
    _level0.gotoAndStop("one");
    But none of these work. There must be a way to do this no?
    Please someone enlighten me! I need all the help I can get.
    Thanks very much for your support,
    Niki

    Hi,
    i don't where you got this code but it looks like Ascript
    used in flash 4...
    and it's full of syntax errors...
    don't know if this is what you want want but why not try
    something like:
    nrOfBtns = 4;
    //position for each button
    // make button on the root like : myBtn. (mClip or Btn clip )
    buttonStep = myBtn._width+10 // or_height
    // for each button make click tag i.e. in an array is allways
    nice
    clickTag = new Array();
    clickTag[0] = "labelName 0";
    clickTag[1] = "labelName 1";
    clickTag[2] = "labelName 2";
    // create loop
    for (i=0; i<nrOfBtns; i++) {
    // gives you myBtn_0 _1 ,etc.
    duplicateMovieClip("myBtn", "myBtn_"+i, i);
    // places each button 0X150 = 0, 1X150 = 150 position etc.
    _root["myBtn_"+i]._x = i*_root.buttonStep;
    // add other things like click commands:
    // like wich label in the root to goto coming from the array
    _root["myBtn_"+i].clickTag = _root.clickTag
    _root["myBtn_"+i].onRelease = function() {
    _root.gotoAndPlay(this.clickTag);
    trace(this.clickTag);
    hope i could help
    ML

  • How can I set 50 variables with the values that are inside an array?

    Hello,
    I have and array of numbers and an array of strings ( the name of the variables) These values are acquired every time from hardware.
    Now I created a graphical interface with 53 of these variables, and I need to create a link to update them with the correct value.
    Thanks
    Dario
    Attachments:
    Example_insert_53_values_in_53_varialbes.vi ‏23 KB

    Dario,
    you have posted your question to the Profibus forum. As your question is not directly related to Profibus, but to LabVIEW programming, your better should post it to the LabVIEW forum.
    Thanks
    Jochen

  • How do i set up to use the spacebar to navigate within an image while using another tool

    when using a tool (such as eraser, clone etc.) i used to be able to navigate within an image by using the spacebar. for some reason, this option is not working any longer and i'd like to know how to set it up again.

    You don't need the background image -- you supply THAT in FCPX. Just work the text effect and publish it.

  • The inspector is staying on top. How do I set it to follow the main window so it is not on top of active app?

    I keep the inspector open when using ical. This problem seems to be new to Lion that the inspector window says topmost even when ical is not active. Any way to change this behavior or is it a bug?

    Go into Settings, General, Dat &amp; Time, and set your time zone to New York.  That will set the correct time.

  • Accessing a class private variable in the main timeline

    Greetings,
    noob question.
    Here's my main class:
    package
         import flash.external.ExternalInterface;
         public class main
             public function main()
             public function check_DVBViewer()
                 ExternalInterface.call("check_DVBViewer","test");
                 ExternalInterface.addCallback("AutoIT",AutoIT);
             private function AutoIT(my_msg:String)
                     // here we get the callback string
    in the timeline I have a dynamic text box named my_textbox:
    var my_test:main = new main();
    my_test.check_DVBViewer();
    my_textbox.text = ???????
    Basically the class waits for the callback variable (my_msg).
    The problem is: I need to set the dynamic textbox text to my_msg variable.
    How can I access it?
    I know I can access a public var in the timeline with functioname.variable but I can't define a public var inside a function, right?
    Thank you very much for your time.

    dispatch an event when the string is ready:
    package
         import flash.external.ExternalInterface;
         public class main
    private var msg:String;
             public function main()
             public function check_DVBViewer()
                 ExternalInterface.call("check_DVBViewer","test");
                 ExternalInterface.addCallback("AutoIT",AutoIT);
             private function AutoIT(my_msg:String)
                     // here we get the callback string
    msg=my_msg;
    dispatchEvent(new Event("stringready"));
    public function get msgF():String{
    return msg;
    in the timeline I have a dynamic text box named my_textbox:
    var my_test:main = new main();
    my_test.addEventListener("stringready",f);
    my_test.check_DVBViewer();
    function f(e:Event):void{
    my_textbox.text = my_test.msgF;

  • 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....

Maybe you are looking for

  • Error message: "Missing required plugins" - Illustrator CS4 will not load OS X 10.4.11

    The install went fine but when I go to load the program I get the an error saying I am missing required plugins (artconverters.aip, pdf format.aip, & rasterize.aip). If I open the package content in finder I can clearly see these files there. I am ru

  • [OpenBox]"Moc Controller" Pipemenu script

    Hey guys, I really like Moc and I use Openbox. My aim was to use Rootmenu to control and see song played. So, I decided to write a script with all fonctions I needed. I just wanna precise that I imagine there is already something like that, but i did

  • Value-based hierarchy on ROLAP dimension. Is this possible and how?

    Value-based hierarchy on ROLAP dimension. Is this possible and how? If yes, what tool I have to use. Any simple examples?

  • Handling big files

    i have file sizes over 100MB to process some transactions. when i open it at one shot, it runs out of memory. i tried opening and splitting it into 1MB each. Even then since the memory is accumulated, it runs out of memory. Is there a way i can open

  • Flash Decompilers for the Mac

    Hi all I'm looking for a decent Flash Decompiler for the Mac. I have a demo of the Gordon Flash Decompiler, but the demo doesn't let me save anything as an fla, which I think is all I want to do with it. Plus I've read more bad than good reviews onli