Thread Objects?

Hi, I need help on making thread objects. I have some code similar to this. It runs as an applet.
//ThreadTest
import java.awt.*;
import java.applet.Applet;
public class ThreadTest extends Applet {
     public void init() {
          new ThreadObject().start();
public void paint(Graphics g) {
g.drawstring(""+i,50,50)
//this is a new file
//ThreadObject
public class ThreadObject extends Thread {
     public ThreadObject() {
          for (int i=0;i>9;i++) {
               System.out.println(i);
Im trying to make this thread just dispay the numbers 1-9 (I understand that it should only print 9 because it prints i to the coordinates 50,50, so the numbers will overlap)
but the screen just stays grey. Ive tried changeing the programs tons of times, but I cant get it to work. Please help!

Ok, first of all, when you extend Thread the code that will be run should be put in the run() method, second, the variable i is only relevent within the for loop, and has nothing to do with the applet, so your line g.drawString(""+i, 50, 50) will not draw i onto the applet, third, there is no code to repaint the applet when you make changes. Take a look at this... I haven't tested it, but it should be about right: //ThreadTest
import java.awt.*;
import java.applet.Applet;
public class ThreadTest extends Applet {
int var = 0; //This varable holds the number to display
  public void init() {
    new ThreadObject(this).start(); /* I'm having this object send a refference
                                    // to itself so the thread has a way to
                                    // call the repaint method */
  public void update(int i) {
    var = i;
    repaint();
  public void paint(Graphics g) {
    g.drawstring("" + var,50,50)
public class ThreadObject extends Thread {
Applet parent;
  public ThreadObject(Applet p) {
    parent = p;
  public void run() {
    for (int i=0;i>9;i++) {
      parent.update(i);
      try {
        Thread.currentThread().sleep(500);/*I'm having the Thread sleep
                                          //for 1/2 second between numbers
                                          */so you can see the numbers change
      } catch(Exception e){System.out.println("Exception: " + e);}
}Like I said, I haven't tested this, so there may be some little problem, but I think that should be about it.
Hope it helps
webaf409java

Similar Messages

  • The thread object

    Hello,
    Is a thread only represented by a single Thread object?
    In other words, when you invoke the Thread.currentThread() method does this method return a reference to the same Thread object that was used to create the thread?
    One more thing, is the Thread object representing a thread ever garbage collected if there are no references to the object?
    Thanks

    Given the fact that the class Thread represents a thread in the JVM, I would conjecture "yes".
    If the thread is still running, any Thread.currentThread() invocation can yield a reference to it, so it is not unreachable and will not be garbage collected.
    Whether a thread will be garbage collected post-mortem, that is, after it exited from its run method, could depend on whether a reference if still held internally by the JVM. There is some internal handling of the threads (let us also think about ShutdownHooks and the like), which might belong to the implementation details of the given JVM.
    I remember some bug with created but not started threads being not garbage collected. They got into some queue of the threads-to-be-started-in-the-future which hampered their being gc'ed.
    while (true) {
        Thread t =new Thread (new MyRunnable());
    }

  • Creating a thread object in ABAP

    Hi,
    Is it possible to create a threa in ABAP function modules or in ABAP objects or in both?
    For example do the following in ABAP code:
    while(true){
    if(someCheck)
    else
    terminate thread
    }thread sleep(1 second)
    regards
    Baran

    There is nothing like threads concept in ABAP.
    But parallel processing can be done like this example:
      DO V_LINES TIMES.
        V_TASK_COUNT = SY-INDEX.
        CONCATENATE 'TASK_' V_TASK_COUNT INTO V_TASK_NAME.
        READ TABLE IT_ARBPL INTO WA_ARBPL INDEX SY-INDEX.
        P_ARBPL = WA_ARBPL-ARBPL.
        REFRESH IT_ORDERS.
        CALL FUNCTION 'ZPP_PARALLEL_PROCESS'
          STARTING NEW TASK V_TASK_NAME
          PERFORMING COLLECT_DATA ON END OF TASK
          EXPORTING
            E_ARBPL   = P_ARBPL
            E_WERKS   = P_WERKS
            E_ZPPUOM  = 'H'
            E_DATES   = IT_DATES
          TABLES
            ET_ORDERS = IT_ORDERS.
        IF SY-SUBRC EQ 0.
          ADD 1 TO V_WC_COUNT.
        ENDIF.
      ENDDO.
      WAIT UNTIL V_WC_COUNT = V_NUMBER_OF_WCS.
    Regards,
    Ravi

  • GUI freezes when new Thread object start()ed. Neat, brief code included :)

    The title says it all really.. I have the code below in a method startScan() that is called when a button is pressed. The thread executes fine, but the GUI locks up while the thread is executing. I don't really understand why, since a new thread is implicitly separate from the event dispatch thread.
    Must I use a SwingWorker to get things working? Would someone be kind enough to explain why, if this is the case?
    private void startScan() throws InterruptedException {
              final Runnable breadthFirstComparer = new Runnable() {
                   /** Sleep interval used when scan paused */
                   private int interval = 1000;
                    * Kills the current thread
                   public void stop() {
                        scanProgressLabel.setText("Scanning complete");
                        scanComplete = true;
                    * Sleeps the currently running thread if user has paused the scan,
                    * otherwise initiates comparison of the trees' next depth node sets
                   public void run() {
                        while (!scanComplete) {
                             while (scanPaused) {
                                  try {
                                       Thread.sleep(interval);
                                  } catch (Throwable exc) {
                                       Gecko.logException("Scanner thread could not be paused", exc);
                             compareTrees();
                        // Stop thread execution once scan is complete, and disable
                        // scanner-related buttons
                        toggleScanButton.setEnabled(false);
                        stop();
              scanner = new Thread(breadthFirstComparer)
                   public void start() {
                        scanProgressLabel.setText("Scanning in progress...");
                        breadthFirstComparer.run();
              scanButton.setEnabled(false);
              scanner.start();
         }Many thanks.

    it's getting really irritating that pretty much every thread out of the last
    20 I've made, you've criticised me for not posting an SSCCE. How do you think I feel. I'm donating my time to help you solve a problem, but you are not willing to spend 5-10 minutes to post a SSCCE so that we can fully understand what you have done and what the problem is.
    You don't have to post a SSCCE if you don't want to. Thats fine, I just won't answer your questions.
    what's the point me spending 30 minutes or more my end creating an
    SSCE, and you spending 10 minutes or more compiling, running and analyzing it your end?It should not take 30 minutes. If it does it just goes to prove that you don't really understand what you are attempting to do. And if you don't know what you are doing how do you expect us to guess what you are doing? One of the benefits of a SSCCE it to help you learn to develop problem solving skills by learning to simplfy the problem.
    Also, what if we can't figure out the problem based on your verbal description of the problem? If you post code it gives us the option of compiling and testing the code if we so desire. Without the code we give up and move on to the next question.
    but since the simple information that you've provided, and the chunk of code that Michal so kindly donated, are likely more than enough of an explanationThis time we were able to guess what the problem was, but that is not true in all cases. You seem to think that we are all miracle workers, that you can place a couple of lines of code in front of us and we can automatically tell whats wrong. Well, thats not true (at least for me). Many times I use my problem solving skills to solve the problem.
    I really should learn to scroll down and read all the posting before replying. es5f2000 pretty much said it all for me.
    Message was edited by:
    camickr

  • THREAD,  OBJECTS,  FOR LOOP

    HI FORM
    I have a method which does some heavy duty mathametical validation and this
    method accepts I/p args from a String[6] for ' n' times avaliable via a for loop .
    1) How to assign this method to run in a threads in parallel ,so the validation is
    avaliable at a same instance .
    Please Do advise me with some code.
    Thx in advance

    I can give more Clarification to this if needed.I think I understand what you're trying to do. Sort of. Enough to suggest how you should do things at least :P
    I'm not entirely sure really that threads are the best way to do this, but I also don't know what I/p stuff is :P
    But if you do go with the threads still, here's how I'd do it.
    for(int row=0; row < rows; row++){
        for (int col=0; col < col; col++) {
            /*this assumes that the textBoxes came from an array,  of the fashion TextBox[rows][cols] which I doubt                 they would.*/
            String text = textBox[row][col].getText()
            Whatever whatever = new Whatever(text);
            Thread t = new Thread(whatever);
            Thread.start();
    }public class Whatever implements Runnable {
    protected String text;
    /** Creates a new instance of Whatever. */
    public Whatever(String text) throws Exception{           
    this.text= text;
    //Whatever this whatever does.
    public void run() {     
    If you want to get the text as well in your whatever, you could pass it enough information to find it.
    As for what you replace my imaginary TextBox array with? I haven't done much with JSPs, and it was quite awhile ago so my memory might be a little fuzzy, but I think you get a Map with key value pairs. In which case you'd do something like
    for (String key: map.keySet()){
        String value=map.getValue(key);
        Whatever= new Whatever(text);
        Thread t = new Thread(whatever);
        Thread.start();
    }Does that help?

  • Thread Methods but in Object class, y?

    Why wait, notify, notifyall methods are in object class instead of Thread class?

    thechad wrote:
    It's not clear to me why. Probably it's a historical artefact .. once it was in Object, it's hard to take it out.
    You're question is a fair question it seems to me. Maybe someone will tell you there's a good reason.Yes, there is a very good reason and it's not a historical artifact.
    wait / notify are used for locking in java. For instance, imagine you have a job queue, and you've got a whole bunch of worker threads that are getting jobs from it. What happens when the queue is empty and there are no more jobs? You want to wait for the queue to have more jobs. Then when a new job comes in, you want to notify any thread waiting that it can now proceed.
    In fact, with reference to why isn't this just handled in thread, it is dangerous and wrong to call wait, notify or notifyall on a Thread object... Thread.join calls wait on the thread and thread death calls notifyAll, but API docs don't guarentee this so you should avoid these methods in a Thread object.

  • Creating array of objects of class which extends Thread

    getting NullPointerException
    can i not create thread array this way?
    class sample extends Thread
    { int i,id;
      public sample(int c)
       { id=c;
      public void run()
      { for(i=0;i<6;i++)
         System.out.println("Thread "+id+" "+i);
    public class thread extends Frame implements ActionListener
    {  Button b1;
       sample s[];
       thread()
       { for(int i=0;i<2;i++)
              s=new sample(i);
         setLayout(new FlowLayout());
         b1=new Button("OK");
         add(b1);
         b1.addActionListener(this);
         public void actionPerformed(ActionEvent e)
         {   b1.setEnabled(false);
              for(int i=0;i<2;i++)
              { s[i]=new sample(i);
              s[i].start();
         public static void main(String args[])
         { thread t1=new thread(); 
         t1.setVisible(true);
         t1.setSize(150,150);

    You need:
    sample [] s = new sample[2];However
    1) You should get into the habit that class names start with capital letters, variable and field names with lower case.
    2) It's not a good idea to extend Thread, make a class which implements the Runnable interface and hook a standard Thread object to that.

  • Shared Objects for Threads

    Hi,
    Currently studying for SCJP exam and wondering is there a different between the following codes
    public class Test extends Thread
    static Object obj = new Object();
    static int x, y;
    public void run()
       synchronized(obj)
         for(;;)
          x++; y++; System.out.println(x+" "+y);
    public static void main(String[] args)
       new Test().start();
       new Test().start();
    }and
    public class Test extends Thread
    Object obj = new Object();
    static int x, y;
    public void run()
       synchronized(obj)
         for(;;)
          x++; y++; System.out.println(x+" "+y);
    public static void main(String[] args)
       new Test().start();
       new Test().start();
    In the first code example, is there a shared object between created threads and the second example, is their still a shared object between threads or is a new object created for each thread?
    Cheers!

    Hi,
    In first case, you are acquiring lock on a static object that is of course shared (basic concept) by all instances(of Test). So, for any thread of any instance(of Test) to execute the synchronized block has to wait till any other thread of any other instance(of Test) comes out of synchronized block. It means, all the instances (of Test) are synchronized. In this scenario, you have infinite for loop within synchronized block and you are starting two threads. The thread which enters the synchronized block first will keep on executing and the other thread will never get chance to enter synchronized block.
    In second case, as you are acquiring lock on an object, all the threads of a particular instance (of Test) will be synchronized. In this scenario, again you have infinite for loop within synchronized block and you are starting two threads on two different instances. Hence, both the threads will keep on executing in parallel.
    I hope, you have already executed both the examples and observed output. And also hope that the above explanation will help you to understand the difference between two scenarios.
    Note: Use System.out.println(Thread.currentThread().getName() + " " + x + " " + y); in your synchronized block to track which thread is printing the output.
    Thanks,
    Mrityunjoy

  • Object Class -Thread

    Hai Respected Friend ,
    I have one doubt regarding Object Class. for what purpose the Object class has some methods like Notify(),Notify All(),wait() though we are not using those methods except with Thread class.
    why they are defined these methods in the Object Class ,why not in the Thread Class even though it is only useful with Thread Class.
    Please give clear ans.
    Thanks
    Selvakumar

    BigDaddyLoveHandles wrote:
    malcolmmc wrote:
    Actually, though these methods are useful only in a multi-threaded environment, no Thread objects are directly involved. What you need to specify isn't a thread object (the current thread is always the one affected) but the monitor, which can be any kind of Object.I would have been happy if they had defined a Lock class with wait and notify methods, because I prefer doing:
    public class C {
    private final Object lock = new Lock();
    public void method() {
    synchronized(lock) {...}
    }to
    public class C {
    public synchronized void method() {
    }In the second case, you have to contend with other code incorrectly calling wait/notify on an instance of C.
    So I don't see the win in these being java.lang.Object methods, other than allowing you to create one less object -- what an efficiency win ;-)However, there are times when it makes sense to expose the lock. For instance Collections.synchronizedXxx.

  • Passing objects to running threads..

    May anybody give me an idea on how to pass an object to an already running thread??
    i only know how to pass an object to the thread's constructor.

    I guess you are trying to assign a variable dynamically. What you can do is a keep a reference in your thread class (you may have probably done it because you have mentioned about passing an object to your threads constructor). Then give a public setter method to assign an object to that variable. Then you can change that even after you invoke start() of your Thread object.
    example:
    public class MyThread extends Thread{
    private Object obj;
    public void setObject(Object obj){
    this.obj = obj;
    public void run(){
    //your code for the thread
    Then from the class you invoke the thread you can do the following:
    MyThread t = new MyThread();
    t.start();
    Object obj = "your object";
    t.setObject(obj);
    Note: However if your thread is not alive when you assign the object then there will be no use of the passed object to the code inside run() method

  • Problem with threads in j2me

    im using jdk 1.6 with java wtk 2.1
    ya i know..
    2.1 is a jdk1.4 source
    but im using souce as 1.4 during compiliation so thats not the prob
    this is my code
    package org.learn;
    import javax.microedition.midlet.MIDlet;
    import javax.microedition.lcdui.Alert;
    import javax.microedition.lcdui.Display;
    public class thtest extends MIDlet
    Thread t;
    public void startApp()
    Alert a=new Alert("hello");
    a.setString("hello");
    Alert b=new Alert("world");
    b.setString("world");
    Display d = Display.getDisplay(this );
    d.setCurrent(a);
    t=Thread.currentThread();
    try{
    t.sleep(10000);
    catch (Exception e){}
    d.setCurrent(b);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
    its just supposed to pause between the alerts using threads
    however when i run it using the wtk, the emulator run properly but when i launch the app, it stops executing giving me this:
    "Error verifying method org/learn/thtest startApp()V
    Approximate bytecode offset 49: Inconsistent or missing stackmap at target
    %the stack info%
    Execution completed.
    437782 bytecodes executed
    9 thread switches
    486 classes in the system (including system classes)
    2506 dynamic objects allocated (73832 bytes)
    2 garbage collections (60652 bytes collected)
    Execution completed.
    437782 bytecodes executed
    9 thread switches
    486 classes in the system (including system classes)
    ALERT: java/lang/VerifyError: org/learn/thtest.
    2506 dynamic objects allocated (73832 bytes)
    2 garbage collections (60652 bytes collected)
    please can someone help me out with this, is it an error on my part or do i have to set some option.

    Hi gandalf123,
    First, Thread.sleep is a static method, so you don't need to create a Thread object to use it.
    I think the problem is due to the fact you don't preverify your midlet.
    More over, you don't need to double post your question.

  • Java threading problem... threads only work on 1 processor

    I've got a iterative deepening problem that i have to parallelize. As far as i know i did everything correctly however everything seems to be running on 1 processor instead of 2 processors. As far as i know i am using threads (-Xprof either defines them as thread-1 thread-2 or pool1-thread1,depending on the method used for issueing)
    the worker thread is:
    public int solutionsT(Board board, int currentDepth) {
            int temp = 0;
            int result = 0;
            if (board.distance() == 0) {
               return 1;
            if (board.distance() > board.bound()) {
                return 0;
            Board[] children = board.makeMoves();
            result = 0;
            for (int i = 0; i < children.length; i++) {
                if (children[i] != null) {
                    temp = solutionsT(children, currentDepth + 1);
    if(temp != 0){
    result += temp;
    return result;
    public void run() {
    int temp =0;
    int i = 0;
    while(true){
    while(bag.size() !=0){
    bag.putSolution(solutionsT(bag.get(),1));
    try{   
    barrier.await();
    }catch(Exception e){}
    it get's it's input from a bag that is filled before the iteration begins. (once the bag is filled it trips a barrier) this worker thread is a implementation of Runnable
    This piece of code is used to make the thread object and to issue it
    public SolutionThread(int numberOfThreads) {
       thread = numberOfThreads;
       bag = new bagOfBoards();
       barrier = new CyclicBarrier(thread+1);
       if(thread > 1){
          ExecutorService threadExecutor = Executors.newFixedThreadPool( thread );
          solution = new ThreadTest[thread];
          bag = new bagOfBoards();
          for(int i = 0;i<thread;i++){
             solution[i] = new ThreadTest(bag, lock, barrier, i);
             threadExecutor.execute(solution);
    finally this is the code which is used to acces the bag and get a board.
    synchronized public Board get() {
                if (size > 0) {
                size--;
                Board result = bag[size];
                return result;
            } else {
             return null;
        }since this method is synchronized and it always returns something (either null or a board) and the worker tests for this. there is no race condition here.
    furter more. the main thread is a loop. It fills te bags with an intial state. then it trips the barrier and waits for the workers to do the work. the workers then process the bag until it hits zero and then trip the barrier so that the main thread can do the next iteration (and fill the bag)
    p.s. i know the code is a bit messy, but i want to get the threading to work. As of now i relaly don't understand why the threads are just running on 1 processor instead of 2 processors. not only that. the excecution time is nearly the same as that of a sequential equivalent.
    p.s.2 the code is parallisable. and it is run on a smp system.
    Message was edited by:
    jstrike

    i'm very sure that the jvm and os support smp. the
    problem really should be in the code.I don't see how this can be the case. There's nothing in the Java language that deals with how threads are assigned to processors (at least not as far as I know) so there isn't anything you can do in your code to affect that.
    Or did you meant that i have to tell the jvm in the class that
    there is support for multiple processorsThat would be the only possibility. I have no idea whether it can be done or not, though.

  • Java API - EventHandler threads not getting killed

    Hello everybody,
    I didn't know whether to post this in the PI forum or in the MDM forum. I use the following scenario:
    We run an EJB session bean in the Java Proxy environment of PI 7.1. In this bean we create an MDM session, log on to a repository and then attach a RecordListener that reacts to any change of the records. When an interesting change took place, the record is distributed to PI.
    The code looks like this:
    EventDispatcher evDis = new EventDispatcher(servername);
    RecordListener recLis = new RecordListener();
    evDis.registerDataNotifications(username, password, repIdent, regions[0]);
    evDis.addListener(recLis);
    The problem arises when we try to undeploy or stop the application. You would assume that it would stop everything connected to the application. However, it does not. The mentioned EventDispatcher creates a thread object when invoked, and this thread is never killed. The consequence: Records keep getting distributed as if nothing had happened, although the application is gone (even undeploying doesn't help). But when we redeploy the application, a new thread is created. So after some development you get 10 or more threads firing every change to PI. The only thing that helps is a restart of the J2EE engine.
    So, my question: Has anybody here made a similar experience? Is this common for MDM or is rather PI the cause of this issue?
    Any comments on that are very welcome.
    Best regards,
    Jörg

    Hi Veera,
    thanks a lot, that pot me on the right track! In fact, it's the @PreDestroy annotation which has to be used for some cleanup method. When we execute this and included the coding you mentioned the threads are killed properly.
    Currently we're facing the issue that somehow the commit status of the bean is not set to "Committed" and from the second message on we get exceptions. If anybody came across this, help is appreciated.
    Best regards,
    Jörg

  • Handling Threads and Memory

    I'm sorry if this is a cross post to my StringBuffer problem. I have run a test that instantiates the object in question and the memory gets collected so I don't think it's that. My question is on how memory pertaining to Threads is handled.
    In my application I have a Thread array that launches X number of Threads. Currently 5. When an object wants a job run, the static Thread pool looks at the current thread and sees if it is still working. If it is, we sleep until it is available. Then I give it another job to do, start it, and move to the next thread.
    Question 1 -
    In a Thread [] is it better to replace the Thread at position x as in
    threads[a] = new Thread();
    threads[a].start();
    or is it better to change some parameter in the thread and then call
    start() again?
    Question 2 -
    I am currently using the second method. In my Thread object I have a MessageObject which contains a StringBuffer, which is eating memory. These MessageObject's are increasing. Some are being collected but many are staying live in the system and causing a memory error. When I do the following....
    MyThread.MessageObject = new MessageObject()
    That should make the original object available for cleanup right?
    Should I call finalize on the MessageObject before replacing it?
    Thanks you for any insights.

    If you want to use thread pools, and you can use JDK 5.0 (formerly known as J2SDK 1.5, codename Tiger), try using the java.util.concurrent package instead of writing your own thread pool (it's really difficult to make a thread pool right).
    If you can't use JDK 5.0, you can try the original util.concurrent package ( http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html ) from Doug Lea. It's used in the JBoss Application Server, so it's tested and reliable.
    If you need to use an object pool, try using the Commons Pool Component from Jakarta Apache: http://jakarta.apache.org/commons/pool/

  • Little bit of thread and little bit of instant messenger design problem

    OK! i have a small problem here, i am planning on making a instant messenger server and client, not compatible with any out there(as of yet) and not using any stansard protocols out there, just something i made on my own. ok now the problem i am trying to figure out is....i have a "Messaging Server" as the name suggests it sends messages from one client to the other, how it is setup is, client connects to this server, the server accepts and creates a new thread for this client and adds a message listener to this client handler thread. as and when the server creates this thread for the client, it puts it in a vector which is keeping track of every client connected to this server. so now when the client sends a message to another client, basically it goes through this server, the thread upon receiving this message, fires a method of the listener. this method takes the message, finds out who it is going to(therefore the userid) and seaches the threads vector to find the appropriate thread and then just creats another striped down message out of the received message and calls a method in that thread to send this newly created message and hence the message should be sent.(i am speculating, i still have not created this)
    so the problem ia m logically facing is...at what point of time who is taking the load, what i mean by that is, when the thread receives the message, ofcourse it is this thread which is working is taking the load, but when the listener fucntion is fired which thread is handlign the call is it the client handler thread which fired the method or the messaging server thread which creates these threads?? now once that is solved, who(which thread) is doing the work when i call the fucntion in the other thread which i found aftre searching the vector. i mean i am thinking like this cuz i am not much in sink with the way threads work. i am also trying to figure out this to find out the load the server or the threads will be having.
    algo example:
    class messageServer
         vector currentWorkingThreads;
         messageListener listener;
         main()
              listener = new messageListener(); //should it be here or the other place i am mentioning below
              while(true)
                   clientHandler = socket.accept();
                   listener = new messageListener(); //should it be here or the other place i am mentioning above
                   //create a thread and add this thread object to the vector
                   thread.addLisenter(listener);
    class messageServerThread
         string userid;
         messageListener lis;
         run()
              object obj = in.readObject();
              lis.sendMessage(obj);
         sendMessage(obj)
              out.writeObject(obj);
              out.flush;
    class messageListener
         sendMessage(msSendMessage msg)
              //find the appropriate user thread
              loop(currentWorkingThread.next())
                   messageServerThread msgThread = (messageServerThread)currentWorkingThread.element();
                   if(msg.userid == msgThread.userid)
                        msReceiveMessage rcvMsg = msg.strip(); //dosent matter what this does, it just strips the unwanted info and returns the type msReceiveMessage
                        msgThread.sendMessage(rcvMsg);
    and if this is something out of the line, or not a good way of doing it, can someone help me with the design it would be gr8.
    thanx a lot
    -Ankur
    help would be greatly appreciated.
    [email protected]

    other, how it is setup is, client connects to this
    server, the server accepts and creates a new thread
    for this client and adds a message listener to this
    client handler thread. as and when the server creates
    this thread for the client, it puts it in a vector
    which is keeping track of every client connected to
    this server.ok so far.
    so now when the client sends a message to
    another client, basically it goes through this server,
    the thread upon receiving this message, fires a method
    of the listener. this method takes the message, finds
    out who it is going to(therefore the userid) and
    seaches the threads vector to find the appropriate
    thread and then just creats another striped down
    message out of the received message and calls a method
    in that thread to send this newly created message andhere you seem to confuse the thread instance and the thread of execution. the thread invoking this method is still the event handling thread (i.e. the receiver thread of the socket). you do not need threads for delivering - this can be done by the receiving sockets' event handling threads. disadvantage: if processing of the message takes significant time then the socket is blocked and cannot process another message.
    solution: put the message in an event queue which is processed by one or more threads. (see my example i e-mailed you)
    robert
    hence the message should be sent.(i am speculating, i
    still have not created this)
    so the problem ia m logically facing is...at what
    point of time who is taking the load, what i mean by
    that is, when the thread receives the message,
    ofcourse it is this thread which is working is taking
    the load, but when the listener fucntion is fired
    which thread is handlign the call is it the client
    handler thread which fired the method or the messaging
    server thread which creates these threads?? now once
    that is solved, who(which thread) is doing the work
    when i call the fucntion in the other thread which i
    found aftre searching the vector. i mean i am thinking
    like this cuz i am not much in sink with the way
    threads work. i am also trying to figure out this to
    find out the load the server or the threads will be
    having.
    algo example:
    class messageServer
    vector currentWorkingThreads;
    messageListener listener;
    main()
    listener = new messageListener(); //should it be
    e here or the other place i am mentioning below
    while(true)
    clientHandler = socket.accept();
    listener = new messageListener(); //should it be
    be here or the other place i am mentioning above
    //create a thread and add this thread object to the
    he vector
    thread.addLisenter(listener);
    class messageServerThread
    string userid;
    messageListener lis;
    run()
    object obj = in.readObject();
    lis.sendMessage(obj);
    sendMessage(obj)
    out.writeObject(obj);
    out.flush;
    class messageListener
    sendMessage(msSendMessage msg)
    //find the appropriate user thread
    loop(currentWorkingThread.next())
    messageServerThread msgThread =
    =
    (messageServerThread)currentWorkingThread.element();
    if(msg.userid == msgThread.userid)
    msReceiveMessage rcvMsg = msg.strip(); //dosent
    ent matter what this does, it just strips the unwanted
    info and returns the type msReceiveMessage
    msgThread.sendMessage(rcvMsg);
    and if this is something out of the line, or not a
    good way of doing it, can someone help me with the
    design it would be gr8.
    thanx a lot
    -Ankur
    help would be greatly appreciated.
    [email protected]

Maybe you are looking for

  • Connect MBP to TV using RCA Cables

    Hi. Is there a way I can connect my MacBook Pro to my older TV just using RCA? Basically I have Red, Yellow and White open ports on my TV and wondered if there was a cable or a converter of some kind that I could connect my computer to and then conne

  • Warning message on creation of IT0105 records

    When I create a IT0105 record, subtype 0004 (phone number) for example and enter a phone number that already exists on another record I get the following message ID/number already used for Person number nnnn.  This is a warning message and I can retu

  • IOS8 bluetooth problem on iPhone 4S

    Apon upgrading to ios8 my iPhone 4S connects to my cars bluetooth car kit (Toyota Venza 2011) but every time I place a call from my car the call drops from my car and i am only able to speak on my phone only.

  • Sudden total failure of all apps that are synced!!!

    After 6 glorious months of no problems, syncing my wonderful office iMac to my trusty old home G3...suddenly today...with no changes or upgrades or new installs...everything which is synced at home launches but will not fully install or show itself i

  • Enter Account Information...? HELP!

    Ok. When I open iTunes, it ALWAYS says to enter my account name and password like it is going to check for purchases. Well I've downloaded everything! How come this box always pops up? Help is appreciated! Thanks!