Vector manipulation for the Thread Class

Hello everyone,
Trying to create a producer consumer class
Please help with consumer method.
Here is my code:
// Class
import java.util.*;
public class ProducerConsumer
     // A private Vector field.
      Vector vector = new Vector();     
           Object element;
     // A flag to indicate completion.
     private boolean produceFlag=false;
     // A method setDone() to indicate completion.
     public void setDone()
          produceFlag=true;
     // A method isDone()  to check completion.
      public boolean isDone()
           if (produceFlag)
                return false;
           else
                return true;
          // A produce() method  - The produce method checks if the vector is empty.
          // If it is, it will get a random number 'x' between 1 and 10.
          // The produce method then gets 'x' number of random numbers between 20 and 30,
          // displays the number on your screen and inserts them into the vector and notify
          // other threads that it is done. If the vector, is not empty then the produce method
          // just waits. You can use the following formula
          // to get random numbers between a range:
     public  synchronized void produce()
     try
          if (vector.isEmpty())                
               int range =1;
               range = (int) (Math.random() * 10);                
               System.out.println("hello" + range);
               for(int i=0;i<range;i++)
                    // convert int to Integer Object.
                    Integer I=new Integer((int) ( ( i - i + 1) * Math.random() + i ));                    
                    vector.addElement(I);                                                            
               //loop thought the elements in a vector to print
               for (int j=0; j < vector.size(); j++)
                    // set reference to each element inside the vector as Object.               
                    element=vector.elementAt(j);
                    /* cast the object variable to Integer.
                    ** call intValue() method of Integer
                    ** object that returns the int
                    ** inside an Integer Object.
                    // print the int just extracted.
                    System.out.println("Integer Found: " + ((Integer) element).intValue());
                    notifyAll();
                    setDone() ;
               else
                    // Vector is not empty - it waits
                    wait();
                    System.out.println("i am not empty");                    
          }          // exception throws by wait().
          catch (InterruptedException e)
               System.out.println(e.toString());
     // A consume method - The consume() method checks
     // if the vector is empty.
     // If it is, it checks if the producer is done.
     // If it is - the program exits.
     // If the producer is not done the consumer just waits. 
     // If the vector is not empty, the consume method
     // retrieves at most three items in FIFO
     // (First In First Out)
     // order from the vector, displays the numbers on your screen
     // and
     //  removes them from the vector.
     // If there are less then three items -
     // the consumer consumes all. If there are more than or
     // equal to three items, the
     // consumer consumes three items.
      public  synchronized void consume()
          try
               if (vector.isEmpty())
                 if (isDone() )
                                System.out.println("Done");
                                System.exit(0);
                      else
                                System.out.println("wait");
                                wait();
               else
                    // Consume retrives at most three items (1in,out)
                    // from vector, display the number on the screen
                    // removes from items from vector
                    // if less then 3 delete them all
                    for (int j=0; j < vector.size(); j++)
                         System.out.println("Integer Found: " + ((Integer) element).intValue());
                         vector.removeElementAt(j);      
          catch (InterruptedException e)
               System.out.println(e.toString());
// exception throws by wait().
}THANKS A LOT FOR YOUR HELP:)

How do I implement the logic to retrieves at most
three items in (First In First Out) and removes them
from the vector.
If there are less then three items - the consumer
consumes all. If there are more than or equal to
three items, the consumer consumes three items.You start by looking at the javadocs for Vector to determine which methods on it might help you....
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html

Similar Messages

  • Class not found exception for the startup class defined.

    iam using weblogic server 10 and bea jrockit 1.5.0.12.
    i have created a startup class in the admin console for a web project and i have deployed the war file using the console in a user defined domains, user project directory.
    when i start the server, iam getting class not found exception for the startup class.
    But, the startup class is available in the web archive (war). how should we add the classes and jars in the war to the classpath in setDomainEnv.sh or is there any other setting available in the console to enable this.

    Hello Julius,
    yes sure, we can move this post to the NW admin forum. I have already posted similar thread on sun forums. I was hoping that someone from SAP SDN already tackled this problem and if not someone specialized in J2EE Engine could troubleshoot me from the class problem I'm getting. I don't know if it's specific from the agent or if this ClassNotFound is a general SAP J2EE Engine error relating to a library not correclty defined.
    Kind regards,
    Tanguy Mezzano

  • Extending the Thread class

    i would like to do that
    1) One thread displays "ABC" every 2 second;
    2) The other thread displays DEF every 5 seconds;
    i need to create the threads by extending the Thread class ...
    thank you for your help ,
                public class Thread1 extends Thread {
              public Thread1(String s ) {
                   super (s);
              public void run() {
                   for ( int i=0; i<5; i++ ) {
                        System.out.println(getName());
                        try {
                           sleep ((long) 5000);
                        } catch (InterruptedException e ) {
                           /* do nothing */
              public static void main (String args[]) {
                   new Thread1 ("ABC").start();
                   new Thread1 ("DEF").start();
         }     

    I think he has been told to use the Thread class by the sounds of it.
    public class Thread1 extends Thread {
         public Thread1(String s ) {
              super (s);
         public void run() {
              for ( int i=0; i<5; i++ ) {
                   System.out.println(getName());
                   try {
                      sleep (getName().equals("ABC")? 5000 : 2000); //If you don't understand this then Google for "Java ternary operator"
                   } catch (InterruptedException e ) {
                      /* do nothing */
         public static void main (String args[]) {
              new Thread1 ("ABC").start();
              new Thread1 ("DEF").start();
    }

  • Application waits for the thread to finish

    Hi all,
    I have a class let say test that extends Thread.
    In my application i say:
    test Xtest = new test();
    Xtest.start();
    System.out.println("Thread finished");
    I need my application to wait for the thread to finish for it to continue, i.e. in my example print "Thread finished" .
    Can someone help me.
    Thanks in advance for your help.
    Best regards,
    Saadi MONLA

    This should work:
    test Xtest = new test();
    Xtest.start();
    Xtest.join();
    System.out.println("Thread finished");

  • Can i create more than one attributes for the custom class created using java API

    Hello everyone,
    I have been creating class and its attributes programatically using java APIs, I want to know that is there any way to create multipal attributs for the same class in just one call of API with all the options for each attributes,
    thanks

    You can create a new class and define all of the Attributes at the time the class is created - this is the preferred way of creating classes. Use the addAttributeDefinition() method on ClassObjectDefinition. If you need to add attributes to existing classes, you can only add them one at a time (using the addAttribute() method on ClassObject).
    (dave)

  • Why system is being allow user twice enrollment for the same Class

    How system allow user to enroll twice for the same class, it's strange for us. These status is being shown under
    the learner tab.
    1.Cancelled from Current Class
    2.Prior Attended (sucessful_attendance_flag = y')
    Could you pls advice, why is showing twice record instead of updation same status by Learner.
    Thanks

    Contact Oracle Support, they can help you.
    Regards Anders Northeved

  • [svn:fx-trunk] 11540: Adding a bunch of ASDoc samples for the following classes:

    Revision: 11540
    Author:   [email protected]
    Date:     2009-11-06 14:27:40 -0800 (Fri, 06 Nov 2009)
    Log Message:
    Adding a bunch of ASDoc samples for the following classes:
        ColorBurnShader.as
        ColorDodgeShader.as
        ColorShader.as
        ExclusionShader.as
        HueShader.as
        LuminosityMaskShader.as
        LuminosityShader.as
        SaturationShader.as
        SoftLightShader.as
    Modified Paths:
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Colo rBurnShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Colo rDodgeShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Colo rShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Excl usionShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/HueS hader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Lumi nosityMaskShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Lumi nosityShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Satu rationShader.as
        flex/sdk/trunk/frameworks/projects/spark/src/spark/primitives/supportClasses/shaders/Soft LightShader.as

  • Any chance you guys are working on vector support for the next update?

    Any chance you guys are working on vector support for the next update? It would definitely make working with these retina displays much easier.

    While waiting, there's this manual solution i proposed here : http://fr32c.free.fr/Am/index.php?post/2013/09/12/Muse-Inline-SVG but you'll have to translate the article. At the bottom are some files to test.
    And i demoed it : http://fr32c.free.fr/Muse/Muse+inlineSVG/

  • How to load classes other than stub classes required for the stub classes

    Can any one pls tell me how to load supporting classes and interfaces for the stubs thru RMI? I am copying necessary stubs and policy file in the client class.
    one of the method of the class returns another supporting class. whenever i invoke this method ot says Class NotFoundException. I dont want to copy these supporitng classes into my client. They are deployment issues involved with this.
    HOW CAN I LOAD THE CLEINT CLASSES THRU RMI

    You should look at the documentation concerning CODEBASE. -Djava.rmi.server.codebase=
    It is too involved to explain it all here.

  • A question about the Thread class

    the code below are two way of invoke a thread to run:
    A:
    public class Test {
    public static void main(String args[]) {
         Thread myThread = new Thread(){
              public void run(){
                   System.out.println("in myThread! \n");
                   System.out.println(Thread.currentThread());
         Thread th = new Thread(myThread,"new Thread");
         th.start();
    B:
    public class Test {
    public static void main(String args[]) {
         Thread myThread = new Thread(){
              public void run(){
                   System.out.println("in myThread! \n");
                   System.out.println(Thread.currentThread());
         myThread.start();
    i have read many free software's source code, and find many people would like to implement it like A instead of B
    so my question is why A is better than B.
    thanks!!

    A is actually using the constructor which accepts a Runnable. In your case, since you are overriding only run(), you could have simply implemented the Runnable and created the thread th. However, in this model you are using a Runnable you are actually separating the task from the Thread. In B, thread is actually the task which couples them tightly. Therefore, from design point of view, A is recommended with Runnable rather than a Thread unless you have specific reasons to do that.

  • Change GL account for the valuation class

    Hi,
    Currently I have a valuation class SUPP which is assign to GL account 14800, now the customer have the request to change it to GL account 14100. There is an option to change it in Config OBYC, but there are a lot of materials involved and a lot of material cost that exist is booked under GL account 14800. Can I just change it OBYC, what's the impact?
    Anyone experienced that before?
    Thanks!

    Hi
    This is normal Phenomenon since under that material type you must be having other valuation classes other than SUPP, and you must have assigned lot other G/L accounts , i.e for G/L recon you need to consider lot of Inventory accounts. Now if you change, during the next recon you just have to add the old entry details along with the new G/L account. No issues at all other than informing and co-ordination with FI guys after you new assignment of the G/L acct for SUPP.
    Best Regards

  • Screen layout for the asset class

    Hi,
    I know the name of the screen layout used for a particular asset class, now in that screen layout I want to see which fields are mandatory and which are not. Where can I see that?
    Please help .
    Many Thanks

    Hi,
    If you want to see the fields in screen layout go to spro - Asset accounting - Master data - screen layout - Define Screen Layout for Asset Master Data - click on Define Screen Layout for Asset Master Data
    there you will find the fields which are mandatory / optional
    Kedar

  • Problems NoClassDefFoundError for the DocumentRange class

    Hi,
    I am trying to launche the ireport application, which uses the xerces.jar, xmlParserAPIs.jar and xalan.jar.
    All these 3 jars are in the classpath, I checked it.
    But I still get a Exception in thread "main" java.lang.NoClassDefFoundError: org/w3c/dom/ranges/DocumentRange
    I tried to put these libraries into the jre/lib/endorsed directory of my JDk (I use 1.4.2_08), but it does not work.
    Someone has an idea of what is a problem?
    Thanks for your help!
    Marie.

    add xml-apis.jar to your classpath.
    Sven

  • Where can I download a WSD device driver for the Image class D1320 printer

    Hope printing carbon good otherwise you try to use printing service.

    You may try getting the driver you want from: http://www.officialdriverdownload.com/.Hope this could work for you.

  • Getting the Adapter Class Not Found Error in the Java Manipulator

    Hi,
    I wrote a custom java manipulator for the baseline update and created a jar file for the class. This works fine in the Windows machine. All I have to do is while specifying the CLASSPATH, I entered the ./ib/newManipulator.jar; ./lib/additional_dependency.jar. When I tried to deploy the same code in the Unix environment, it fails saying the Adapter Class not found. The only difference from windows and Unix environment is that in the windows machine, in order to run the base line update, I go to the directory my_project->control->baseline_update.bat but in case of Unix environment I have a separate location where I have a shell script called run-baseline-update.sh located at /apps/bin which invokes the baseline.sh in the directory my_project/control/baseline.sh. I even tried to put the full path of the jar files e.g. /my_project/lib/newManipulator.jar; /my_project/lib/additional_dependency.jar in the class path but still the same issue. Any suggestions?

    Unix classpath needs ":" as the path separator, not ";". Changing that will make this work.
    For reference, later versions of the deployment template make this configurable, so you'd see (in environment.properties):
    # PATH_SEP_VARNAME: for platform-independence
    PATH_SEP_VARNAME=;
    # Forge needs record store libraries as well as Spring to load record store adapter configuration files
    FORGE_CLASSPATH=./config/lib/java/spring-delegate-adapter-1.0.1.jar${PATH_SEP_VARNAME}./config/lib/java/spring.jar${PATH_SEP_VARNAME}./config/lib/java/eacToolkit.jar${PATH_SEP_VARNAME}./config/script${PATH_SEP_VARNAME}.
    You can then add the following to your <forge /> definition in AppConfig.xml:
    <arg>--javaClasspath</arg>
    <arg>${FORGE_CLASSPATH}</arg>
    Hope this helps.
    Michael

Maybe you are looking for

  • WHT on advance payment

    Hi, I have configured WHT for customers on gross up basis. WHT is posting to clearing account at the time of advance payment receipt. But the same is not reversing at the time down payment transfer using F-39 transaction. What could be the reason for

  • Global Variable in Progress Bar

    I have an existing labview code that is comprised of a main vi, which is the user GUI, and several (approx 70) sub vi's. I am trying to add a progress bar to the front screen (User GUI) that will immediately increment after it hits certain sections o

  • Recursive ctags under solaris 10

    Hi, i am new to solaris development. Under linux for recursive ctags we use " ctags -r .". What will be the equivalent recursive ctags under solaris 10 ? With thanks in advance, Barun Parichha

  • Printer option in selection screen (Input Parameter)

    Hi All, I want to give printer option in selection screen. Please do needful help. Regards.

  • Displaying all rows if value is blank

    Hi all trying I am trying to display all the rows from a database if the default value is blank I have tried to put a * or ? in the php code What could be wrong here? What do I need to put for the variable section for the correct syntax As it its Nam