Two threads in the same class ? Is that possible ?

Hello, I am trying to use threads to move two images around the frame. And I am wondering if it is possible if it is possible to create two separate threads that act differently in the same class, for each of the image.
Is just that so far I can't see a way since, by implementing Runnable, I'll need to overwrite the run() method. Which in a way just allows me to manage one image.
Of course I can do two separate classes (each implementing Runnable) for each of the image, but since I think it may be an overkill, I rather to do it in just one.
So, is that possible ?
Thank you in advance.

Of course I can do two separate classes (each implementing Runnable) for each of the image,Use two instances of the same class. Something like this example:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=631379

Similar Messages

  • Two Threads Sharing the Same Object

    I am learning Java multithreading recently and I really hit the wall when I came to synchronizing data using the synchronized keyword. According to the explanation, synchronized will only work when 2 or more threads are accessing the same object. If there are accessing 2 different objects, they can run the synchronized method in parallel.
    My question now is how to make sure for synchronized method to work, I am actually working with the same and only one object??
    Imagine this:
    Two person with the same account number are trying to access the very ONE account at the same time.
    I suppose the logic will be:
    Two different socket objects will be created. When it comes to the login or authentication class or method, how can I make sure in term of object that the login/authentication class or method will return them only ONE object (because they share the same account), so that they will be qualified for using the synchronized method further down the road?
    Thanks in advance!

    Actually your understanding is wrong. Consider:
    public class MyClass {
      private int someInt;
      private float someFloat;
      private synchronized void someMethod(final int value) {
        if (value > 2000) someInt = 2000;
      private synchronized void someOtherMethod(final float value) {
        if (value > 2.0) someFloat = 1.999f;
    }YOu might think that two different threads can enter this code, one can enter in someOtherMethod() while one is in someMethod(). That is wrong. The fact is that synchronization works by obtaining synchronization locks on a target object. In this case by putting it on the method declaration you are asking for the lock on the 'this' object. This means that only one of these methods may enter at a time. This code would be better written like so ...
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) someInt = 2000;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) someFloat = 1.999f;
    }In this manner you are only locking on the pertinent objects to the method and not on 'this'. This means that both methods can be entered simultaneously by two different threads. However watch out for one little problem.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized(someInt) {
          if (value > 2000) {
            someInt = 2000;
            synchronized (someFloat) {
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this case you can have a deadlock. If two threads enter one of these methods at the same time one would be waiting on the lock for someInt and the other on the lock for someFloat. Neither would proceed. The solution to the problem is simple. Acquire all locks in alphabetical order before you use the first.
    public class MyClass {
      private int someInt;
      private float someFloat;
      private void someMethod(final int value) {�
        synchronized (someFloat) {
          synchronized(someInt) {
            if (value > 2000) {
              someInt = 2000;
              someFloat = 0.0f;
      private void someOtherMethod(final float value) {
        synchronized(someFloat) {
          if (value > 2.0) {
            someFloat = 1.99999f;
            synchronized (someInt) {
              someInt = 0;
    }In this manner one thread will block waiting on someFloat and there can be no deadlock.

  • How to Differntiate between two instances of the same class ????

    I don't even know if my question makes sense or not ??
    I don't have any code written for it yet.. but its the most critical task for me..
    Q ??
    say i have multiple objects running of the same class on the same box.
    sth like a CPU can have multiple ports. The port class is intantiated
    to create every new port for CPU as required.
    Now i have to differntiate multiple ports on that box and give
    accordingly its statistics back to CPU. sth like how many acces to
    ports, how much bandwidth available, how many bits.. i know how to
    calculate statistics of ports but i don't know how to differentiate
    between multiple ports ??
    Eg: Number of sessions created on oneport is 14 and other is 25. Then i
    have to give differnt statistics of these 2 ports back to CPU.
    I hope all this made some sense ???
    Thank youuuuu....reply back if u need some more details....
    Edited by: javanewbie83 on Jun 16, 2008 4:28 PM

    javanewbie83 wrote:
    I don't even know if my question makes sense or not ??
    I don't have any code written for it yet.. but its the most critical task for me..
    Q ??
    say i have multiple objects running of the same class on the same box.
    For an example: (its just a correlation to my project.. its actually not CPU and port numbers.. sorry if u misunderstand...)
    sth like a CPU can have multiple ports. The port class is intantiated
    to create every new port for CPU as required.
    Now i have to differntiate multiple ports on that box and give
    accordingly its statistics back to CPU. sth like how many acces to
    ports, how much bandwidth available, how many bits.. i know how to
    calculate statistics of ports but i don't know how to differentiate
    between multiple ports ??
    Eg: Number of sessions created on oneport is 14 and other is 25. Then i
    have to give differnt statistics of these 2 ports back to CPU.
    I hope all this made some sense ???
    Thank youuuuu....reply back if u need some more details....Simply repeating your unclear original post does not magically make it clear.

  • How to start two threads at the same time

    Hi there,
      I want to include multithreading in the CVI program. I have two tasks which has no dependence between them, so I would like to start two threads for perform the tasks. I follow the introduction http://www.ni.com/white-paper/3663/en/ to start my code. In my code, I add a command button, when it is pressed, I create two threads to perform the tasks. In each task, I have a big loop and in each iteration, I use ProcessSystemEvents to avoid no response on system message. But it doesn't work actually, the program suspended. I wonder must I initialize the threads in main. I am looking for a way to start the threads in the callback function for a button since I am not starting those threads at the beginning but while it is triggered.
    the main frame of the code looks
    int CVICALLBACK Test1(void *functionData)
    { int i=0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK Test2(void *functionData)
    int i = 0;
    for (i = 0; i<100000; i++) {ProcessSystemEvents();}
    return 0;
    int CVICALLBACK cmdcb(int panel, int control, int event, void *callbackData, int eventData1, int eventData2)
    { int threadID1, threadID2;
    if (event==EVENT_COMMIT)
    SetPanelAttribute(panelHandle, ATTR_DIMMED, 1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test1, NULL, &threadID1);
    CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, Test2, NULL, &threadID2);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID1, 0);
    CmtWaitForThreadPoolFunctionCompletion (DEFAULT_THREAD_POOL_HANDLE, threadID2, 0);
    return 0;
    Attachments:
    TestThread.zip ‏239 KB

    In my opinion your threads may be simply lasting longer than expected due to an incorrect sleep policy of threads paired with with ProcessSystemEvents () in the loop.
    I made up a quick example that shows this behaviour: playing with "Do not sleep" and "Call ProcessSystemEvents" options you can see how threads execute.
    BTW: do not forget to release the thread function IDs at the end of functions.
    Proud to use LW/CVI from 3.1 on.
    My contributions to the Developer Zone Community
    If I have helped you, why not giving me a kudos?
    Attachments:
    thread.zip ‏7 KB

  • How to avoid two threads creating the same entity?

    I seem to have a problem with a race-condition. Two threads are trying to
              create the same entity. One thread calls a finder with no success and
              creates the entity, meanwhile - before the entity gets persisted
              (ejbStore()) - the other thread also calls a finder with no success,
              creating the
              same entity.
              My transaction isolation level in the weblogic-ejb-jar.xml is
              <transaction-isolation>
              <isolation-level>TRANSACTION_READ_UNCOMMITTED</isolation-level>
              <method>
              <ejb-name>ejb</ejb-name>
              <method-name>*</method-name>
              </method>
              </transaction-isolation>
              I've also tried <isolation-level>TRANSACTION_SERIALIZABLE</isolation-level>
              with no significant change in behavior.
              In the ejb-jar.xml
              <container-transaction>
              <method>
              <ejb-name>ejb</ejb-name>
              <method-name>*</method-name>
              </method>
              <trans-attribute>Required</trans-attribute>
              </container-transaction>
              

              Try setting delay-updates-until-end-of-tx to false for your bean. Try experimenting
              with concurrency-strategy of Exclusive. Or re-write your code to not check for
              existence before creation; just create the bean and let the db return a duplicate
              key exception.
              simon.
              "Daniel" <[email protected]> wrote:
              >I seem to have a problem with a race-condition. Two threads are trying
              >to
              >create the same entity. One thread calls a finder with no success and
              >creates the entity, meanwhile - before the entity gets persisted
              >(ejbStore()) - the other thread also calls a finder with no success,
              >creating the
              >same entity.
              >
              >My transaction isolation level in the weblogic-ejb-jar.xml is
              ><transaction-isolation>
              ><isolation-level>TRANSACTION_READ_UNCOMMITTED</isolation-level>
              ><method>
              ><ejb-name>ejb</ejb-name>
              ><method-name>*</method-name>
              ></method>
              ></transaction-isolation>
              >
              >I've also tried <isolation-level>TRANSACTION_SERIALIZABLE</isolation-level>
              >with no significant change in behavior.
              >
              >In the ejb-jar.xml
              ><container-transaction>
              ><method>
              ><ejb-name>ejb</ejb-name>
              ><method-name>*</method-name>
              ></method>
              ><trans-attribute>Required</trans-attribute>
              ></container-transaction>
              >
              >
              

  • One Listener : two Databases in the same system : is it possible ?

    Hi,
    I am trying to setup a single listener to listen to two Databases running in the same system. We are experimenting a Network Architecture & this is a part of our experiment to see what happens..( most of the documentation I have read point out that running two DBs on a sing le system isn't a good idea..).
    One of the Databases is an Oracle Application Server Infrastructure Metadata Respository ( OraInfra ). The other database has been configured for use with Oracle Content Database ( OraContentDB ) .
    The two databases are up & running successfully - however, the problem is with the listener. The two listener.ora files are as follows :-
    # listener.ora Network Configuration File: C:\oracle\product\10.2.0\OraContentDB\network\admin\listener.ora
    # Generated by Oracle configuration tools.
    SID_LIST_LISTENER =
      (SID_LIST =
        (SID_DESC =
          (SID_NAME = PLSExtProc)
          (ORACLE_HOME = C:\oracle\product\10.2.0\OraContentDB)
          (PROGRAM = extproc)
    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
          (ADDRESS = (PROTOCOL = TCP)(HOST = 152.69.191.100)(PORT = 1522))
      )and
    # listener.ora Network Configuration File: C:\OraInfra\network\admin\listener.ora
    # Generated by Oracle configuration tools.
    SID_LIST_LISTENER =
      (SID_LIST =
        (SID_DESC =
          (SID_NAME = PLSExtProc)
          (ORACLE_HOME = C:\OraInfra)
          (PROGRAM = extproc)
    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS_LIST =
            (ADDRESS = (PROTOCOL = TCP)(HOST = 152.69.191.100)(PORT = 1521))
            (ADDRESS = (PROTOCOL = TCP)(HOST = 152.69.191.100)(PORT = 1522))
          (ADDRESS_LIST =
            (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC))
      )However, everytime I try to connect via SQLPLUS, I can only connect via the first Listener. If I try to connect via the second listener, I only get this error :-
    SQL> connect scott/tiger@localhost:1522/CONTENTDB
    ERROR:
    ORA-12541: TNS:no listenerCan anyone shed some light on this ?
    Thanks,
    Sandeep

    Hi,
    Thanks to everyone for your time ! Yes, I now have an understanding of the architecture & I am trying to set up my listener...
    Paul, I reconfigured my Listener.ora and started it :-
    SID_LIST_LISTENER =
      (SID_LIST =
        (SID_DESC =
          (SID_NAME = PLSExtProc)
          (ORACLE_HOME = C:\OraInfra)
          (PROGRAM = extproc)
        (SID_DESC =
          (GLOBAL_DBNAME = ORAINFRA.idc.oracle.com)
          (ORACLE_HOME = C:\OraInfra)
          (SID_NAME = ORAINFRA)
        (SID_DESC =
          (GLOBAL_DBNAME = CONTENTDB.idc.oracle.com)
          (ORACLE_HOME = C:\oracle\product\10.2.0\OraContentDB)
          (SID_NAME = CONTENTDB)
    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS_LIST =
            (ADDRESS = (PROTOCOL = TCP)(HOST = 152.69.191.100)(PORT = 1521))
          (ADDRESS_LIST =
            (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC))
      )I started the listener from the command line and this si what I see :-
    C:\OraInfra\bin>c:\OraInfra\bin\lsnrctl
    LSNRCTL for 32-bit Windows: Version 10.1.0.4.2 - Production on 16-AUG-2006 10:12
    :38
    Copyright (c) 1991, 2004, Oracle.  All rights reserved.
    Welcome to LSNRCTL, type "help" for information.
    LSNRCTL> start
    Starting tnslsnr: please wait...
    TNSLSNR for 32-bit Windows: Version 10.1.0.4.2 - Production
    System parameter file is C:\OraInfra\network\admin\listener.ora
    Log messages written to C:\OraInfra\network\log\listener.log
    Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=152.69.191.100)(PORT=152
    1)))
    Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROCipc)
    Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=152.69.191.100)(PORT=152
    1)))
    STATUS of the LISTENER
    Alias                     LISTENER
    Version                   TNSLSNR for 32-bit Windows: Version 10.1.0.4.2 - Produ
    ction
    Start Date                16-AUG-2006 10:12:45
    Uptime                    0 days 0 hr. 0 min. 2 sec
    Trace Level               off
    Security                  ON: Local OS Authentication
    SNMP                      OFF
    Listener Parameter File   C:\OraInfra\network\admin\listener.ora
    Listener Log File         C:\OraInfra\network\log\listener.log
    Listening Endpoints Summary...
      (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=152.69.191.100)(PORT=1521)))
      (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROCipc)))
    Services Summary...
    Service "CONTENTDB.idc.oracle.com" has 1 instance(s).
      Instance "CONTENTDB", status UNKNOWN, has 1 handler(s) for this service...
    Service "ORAINFRA.idc.oracle.com" has 1 instance(s).
      Instance "ORAINFRA", status UNKNOWN, has 1 handler(s) for this service...
    Service "PLSExtProc" has 1 instance(s).
      Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
    The command completed successfully
    LSNRCTL>It didn't look suspicious to me I had a peek at the Listener.Log :-
    TNSLSNR for 32-bit Windows: Version 10.1.0.4.2 - Production on 16-AUG-2006 10:12:43
    Copyright (c) 1991, 2004, Oracle.  All rights reserved.
    System parameter file is C:\OraInfra\network\admin\listener.ora
    Log messages written to C:\OraInfra\network\log\listener.log
    Trace information written to C:\OraInfra\network\trace\listener.trc
    Trace level is currently 0
    Started with pid=3308
    Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=152.69.191.100)(PORT=1521)))
    Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROCipc)))
    TIMESTAMP * CONNECT DATA [* PROTOCOL INFO] * EVENT [* SID] * RETURN CODE
    16-AUG-2006 10:12:45 * (CONNECT_DATA=(CID=(PROGRAM=)(HOST=)(USER=balajsub))(COMMAND=status)(ARGUMENTS=64)(SERVICE=LISTENER)(VERSION=168821762)) * status * 0
    16-AUG-2006 10:12:46 * service_died * 1183The message "service_died" looked fishy & I tried to conect :-
    C:\OraInfra\bin>sqlplus /nolog
    SQL*Plus: Release 10.1.0.4.2 - Production on Wed Aug 16 10:18:26 2006
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    SQL> connect scott/[email protected]:1521/ORAINFRA.idc.oracle.com
    SQL> Connected
    SQL> connect scott/[email protected]:1521/CONTENTDB.idc.oracle.com
    ERROR:
    ORA-12537: TNS:connection closedI now understand that the Listener is trying to open a connection to the Database - but, I am not sure why the connection dies with with the ORA-12537 error. It looks like the error is somewhere deeper in the TNS Layer...
    Can you throw some light on this as well ?
    Regards,
    Sandeep

  • Two messengers at the same time. A possibility?

    Hey gang
    I have a question... I have my regular MSN, but I also have one for my business, and I would like them both to be online at the same time... The MSN Messenger I have feature a window for "personal contacts" and one named "Company account" so I thought that was perfect. Unfortunately, I cannot sign in on the one named "Company account", even though the MSN I have created works fine in the "personal contacts" window...
    Any suggestions?

    I don't use messenger much, but in iChat, when I log in with my other computer, a message appears asking if I approve multiple log ins. Possibly there's a messenger setting somewhere that permits the same?

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

  • Aperture in two machines sharing the same library... possible?

    I want to have one library which I could share between two machines (Ive got an iMac and a MBP). But I'd like to keep the library in iMac and access it on MBP over the network. I don't need use it simultaneously, but I don't want to use an external drive for it either... Any ideas? Thanks

    Ian, and others,
    I am maintaining multiple boot volumes on my Mac Pro, with the primary ones being one for Tiger and one for Leopard. At the moment I am separately maintaining Photoshop CS3 and Final Cut Studio on each of those. I have recently installed Aperture on that Leopard boot. I now plan to establish another Leopard boot (using a WD 750 GB drive), primarily for the pro apps such as PS CS3, Aperture and Final Cut Studio 2 (an upgrade) while maintaining FCS 1 on the other boot drive. With FCP, the projects and voluminous files are of course maintained on drives other than the boot volumes, and thus FCP, for example, can use those files whether I am in the Tiger boot, or the Leopard boot.
    I have been wanting to fire up Aperture while in the Tiger boot, to test some odd printing behavior, but don't want to create another Aperture Library (which is not yet populated to any real extent) just to do the test. Also, I would like to administer the Aperture Library from the planned new Leopard boot, but not create separate libraries if I should wish to use Aperture while in other boot volumes.
    It seems clear (but I could be wrong) that this can be done, but is it advisable? Practical? Obviously, with the separate boots, I would never be using Aperture from but one "computer".
    Ernie

  • Can multiple threads share the same cursor in berkeley db java edition?

    We use berkeley db to store our path computation results. We now have two threads which need to retrieve records from database. Specifically, the first thread accesses the database from the very beginning and read a certain number of records. Then, the second thread needs to access the database and read the rest records starting from the position where the cursor stops in the first thread. But, now, I cannot let these two threads share the same cursor. So, I have to open the database separately in two threads and use individual cursor for each thread. This means I have to in the second thread let the cursor skip the first certain number of records and then read the rest records. However, in this way, it is a waste of time letting the second thread skip a certain of records. It will be ideal for us that the second thread can start reading the record just from the place where the first thread stops. Actually, I have tried using transactional cursor and wanted to let the two threads share the same transactional cursor. But it seems that this didn't work.
    Can anyone give any suggestion? Thank you so much!
    sgao

    If your question is really about using the BDB Java Edition product please post to the JE forum:
    Berkeley DB Java Edition
    If your question is about using the Java API of the BDB (C-based) product, then this is the correct forum.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to use the TableSorter for two tables at the same view?

    Hello,
    I am using the TableSorter object in order to sort Dynpro tables.
    Suppose I have two tables at the same view, is it possible to use it seperatly for both of them?
    I assume that at the wdModifyView method I will need to catch the table that the user clicked on, yet I don't have an idea of how to do it...

    Hi Roy,
    Constructor of TableSorter
    public TableSorter(IWDTable table, IWDAction sortAction, Comparator[] comparators)
    So, you have to create instance of TableSorter class for each table on the view.
    best regards, Maksim Rashchynski.

  • Sync a folder between two users on the same computer.

    I would like to sync a folder between two users on the same computer so that they are always the same when I access them from either user.

    then place this folder somewhere where both users have access to like in /Users/Shared. then there is only one folder to deal with and you don't need to sync anything.

  • Bluetooth - Connecting two devices at the same time on a Run (Bluetooth Mot headset

    I would like to connect two Bluetooth devised at the same time on my runs.  (Bluetooth Motorola headset (S10-HD) and Polars heart monitor (H7) at the same time)  is that possible? 

    fitnessdr wrote:
    Thank you for the information.  So if I were to return the new bluetooth keyboard, should I purchase the "Palm 3169WWZ Wireless Keyboard", or is there another model I should be looking for?  (From what I can tell, I believe this one will use IR.)
    THANKS!
    Correct, that's the one I use. 
    Be sure to download the newest driver (1.13) for the keyboard from the Palm Support pages for the keyboard:
    http://kb.palm.com/wps/portal/kb/na/keyboards/palmuniversalwirelesskeyboard/unlocked/downloads/page_...
    Do not install the driver that comes with the device on the disk - 1.13 is designed for the TX and fixes a bug that existed in the original driver.
    WyreNut
    I am a Volunteer here, not employed by HP.
    You too can become an HP Expert! Details HERE!
    If my post has helped you, click the Kudos Thumbs up!
    If it solved your issue, Click the "Accept as Solution" button so others can benefit from the question you asked!

  • Communication between thread in the same process using file interface.

    Hi,
    I am developing  driver and i need to communicate between two thread.
    >can anyone guide me on implementing communication between two thread in the same process using File Interface. First thread will be driver and second will be application.I need to send IOCTL like commands using File interface ie is WriteFile(),ReadFile()
    from Host process to driver through file-interface(which run's in driver context).Host process should not be blocked for the duration of the driver to process the command.
    >File-interface will run in driver context and it will be responsible to receive command from application and pass it to the driver.
    what are the complexity introduced?
    >Can anyone also give me the link/reference to get more information on this topic?
    >How to replace IOCTL command's for instance baud _rate change command with a file interface for example with IRP.

    Here  is the detailed query:
    Hardware Abstraction Layer will interact with Driver(Both will be running in complete different process) .there is a IOCTL for command and  File interface for read and write.
    My requirement is:
    Both should run in the same process so HAL will run as one thread and driver as another thread in the same process .I don't want HAL to wait for completion of request and also i don't want driver to be blocked .
    We are planning to use a File Interface for communication between Hardware abstraction layer and Driver
    HAL will send the command or read/write operation to a file interface and driver will get the command or read/write request from the File interface
    There is a flexibility to change Hardware Abstraction layer and also the Driver
    Is it possible to use IOCTL between two thread under same process? if not what other options do we have.
    Can we use File interface to  send command (like IOCTL) between two thread?

  • Two different Routers and same subnet, is it possible?

    Hi i have been presented with a problem that a friend of mine is having.
    There is two different Cisco routers on different location.
    example:
    router1 : 10.8.10.1 (has DHCP/FTP server)
    router2 : 10.8.12.1 (needs to talk to DHCP/FTP server on router1)
    the router2 has different ip configured but is it possible to change this to the same subnet as router 1? like 10.8.10.4?
    The DHCP/FTP server have been defined with scope 10.8.12.0 and on the Cisco switch on router2 its been configured (ip helper address DHCP-IP)
    this works, the clients connected to router2 gets ip from DHCP server ,but there is no FTP traffic.
    i figure its because the DHCP/FTP server doesent understand the other IP, so if its possible to setup a kind of mulitVPN to get the same subnet on router2 as router1 the FTP server can "see" the other router2 because it has the same subnet and ip range.
    Thank you for any experience, i really stuck on this one

    John,
    to simply put it having two routers on the same subnet is not possible as the purpose of a router is to route traffic between DIFFERENT networks. In order to accomplish this you will need routers and switches that understand VLANs and VLAN tagging.
    Hope this Helps
    Blake Wright
    Cisco SBSC Network Engineer

Maybe you are looking for

  • How to extract data from a column after triming some characters

    idx address 987     LOT 32 THE LAKES WAY      1113     LOT 88 UMOONA ROAD      930     LOT 1 PACIFIC HIGHWAY      1022     LOT 5 SYDNEY ROAD      1085     LOT 10 MOUNT BARKER ROAD      1122     LOT 653 BANDICOOT DRIVE      The above is my table and i

  • Network Printing... "Cannot Find Server"

    I am having trouble in having my printer be a... "Network Printer"-.  It is a HP Laserjet 2015 Printer. I have a Mac OS version ~ 10.8.2..... If i have the printer connect directly to the computer via USB, (with no network) the printer works fine, bu

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this... [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html] I was reading the documentation and I read

  • Wlan connection slow

    Hi, since a few days I have big problems with the WLAN-connection of my late 2011 13" Macbook Pro that leads to very slow Intenet Connections and Slow SMB-Server access. In Detail: If I will open a Webpage it will take 50 times longer then from my iP

  • SAP Query: Display Selection Fields in the header page of Basic list

    Hello, I have to display the selection fields in the header page of the basic list and statistics in a SAP Query. I know the usage of short names for fields in the header page, but this doesn't work for the selection fields. How can I display the sel