Thread and Runnable

Can anyone please tell me why this code is not executing
FirstClass second=new FirstClass("i m 2nd class");
     second.run();
in the below program.
its show the output like:
i m 3rd class
i m 4rd class
i m in threadi m 3rd class 0
i m 1st class
i m runnablei m 1st class 0
i m in threadi m 4rd class 0
i m runnablei m 1st class 1
i m in threadi m 3rd class 0
i m runnablei m 1st class 2
i m in threadi m 4rd class 0
i m runnablei m 1st class 3
i m in threadi m 3rd class 0
i m runnablei m 1st class 4
i m in threadi m 4rd class 0
i m runnablei m 1st class 5
i m in threadi m 3rd class 0
i m runnablei m 1st class 6
i m in threadi m 4rd class 0
but it didnot tell me about 2nd runnable class why ?
public class MainClass {
public static void main(String[] args) {
     SecondClass third=new SecondClass("i m 3rd class");
     third.start();
     SecondClass fourth=new SecondClass("i m 4rd class");
     fourth.start();
     FirstClass first=new FirstClass("i m 1st class");
     first.run();
     FirstClass second=new FirstClass("i m 2nd class");
     second.run();
class FirstClass implements Runnable{
     private int count;
     private String sq;
     public FirstClass(String str) {
          count=0;
          sq=str;
          System.out.println(str);
public void run() {
     while(true){
     System.out.println("i m runnable" + sq+ " " +count);     
     try {
     count++;
Thread.sleep(500);
     } catch (InterruptedException e) {
class SecondClass extends Thread {
     private int count;
     private String sq;
     public SecondClass(String str) {
          count=0;
          sq=str;
          System.out.println(str);
public void run() {
while(true){
     System.out.println("i m in thread" + sq+ " " +count);
     try {
     Thread.sleep(1000);
     } catch (InterruptedException e) {
}

The reason behind this is that, whenever you implement Runnable in a class and invoke the run() method, no other threads can start after that call. So when you invoke first.run(), the thread "i m 2nd class" doesn't start, i.e,
SecondClass third=new SecondClass("i m 3rd class");
third.start();
SecondClass fourth=new SecondClass("i m 4rd class");
fourth.start();
FirstClass first=new FirstClass("i m 1st class");
first.run();
// this thread won't start and hence the result
FirstClass second=new FirstClass("i m 2nd class");
second.run();
If you had called the run() at the beginning of the program, then neither of the threads would have started
FirstClass first=new FirstClass("i m 1st class");
first.run();
// none of the threads would start
SecondClass third=new SecondClass("i m 3rd class");
third.start();
SecondClass fourth=new SecondClass("i m 4rd class");
fourth.start();
FirstClass second=new FirstClass("i m 2nd class");
second.run();
and that's the reason for your output!

Similar Messages

  • Difference bet Thread and Runnable Inteface

    what is the main difference bet Thread and Runnable interface. Where it is used Thread and Where it is used Runnable interface

    http://www.javaworld.com/javaworld/jw-04-1996/jw-04-threads.htmlThere are a lot of differences, see the article above for details.
    Generally, I would only extend Thread if I want to enhance/extend the functionality of how Threads work (like providing a Timer or a Clock, or something). If all I am doing is providing some work to be done in a separate thread, then I will create a class that implements Runnable and run it using new Thread(myRunnable).start(). Most of the time, I use Runnable, since rarely would I need to change how threads act.

  • Thread vs Runnable

    Hi All,
    I know the basic difference between Thread and Runnable. If my class is extending some class but still we need to make it Thread, then we should use Runnable otherwise we can use any one.
    But specifically I want to know is extending Thread gives any added advantage rather then implementing Runnable.
    Please let me know the answer.
    Regards,
    Gourab

    Pls refer to follwing link....
    http://forum.java.sun.com/ann.jspa?annID=9
    Hope you get your answer.
    ~ANil

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Having a problem with threads and using locks

    I was hoping someone could give me some hits on getting my code to run properly. The problem I am having is I think my locks and unlocks are not working properly. Plus, for some reason I always get the same output, which is:
    Withdrawal Threads         Deposit Threads            Balance
    Thread 2 attempts $29 Withdrawal - Blocked - Insufficient Funds
    Thread 4 attempts $45 Withdrawal - Blocked - Insufficient Funds
    Thread 6 attempts $34 Withdrawal - Blocked - Insufficient Funds
    Thread 7 attempts $40 Withdrawal - Blocked - Insufficient Funds
                                    Thread 1 deposits $187          $187
                                    Thread 3 deposits $169          $356
                                    Thread 5 deposits $61           $417
    Press any key to continue...If someone can see the error I made and doesn't mind explaining it to me, so I can learn from it, I would appreciate that very much.
    /************Assign2_Main.java************/
    import java.util.concurrent.*;
    public class Assign2_Main
    {//start Assign2_Main
        public static void main(String[] args)
        {//start main
               // create ExecutorService to manage threads
               ExecutorService threadExecutor = Executors.newCachedThreadPool();
            Account account = new SynchronizedThreads();
            Deposit deposit1 = new Deposit(account, "Thread 1");
            Deposit deposit2 = new Deposit(account, "Thread 3");
            Deposit deposit3 = new Deposit(account, "Thread 5");
            Withdrawal withdrawal1 = new Withdrawal(account, "Thread 2");
            Withdrawal withdrawal2 = new Withdrawal(account, "Thread 4");
            Withdrawal withdrawal3 = new Withdrawal(account, "Thread 6");
            Withdrawal withdrawal4 = new Withdrawal(account, "Thread 7");
            System.out.println("Withdrawal Threads\t\tDeposit Threads\t\t\tBalance");
            System.out.println("------------------\t\t---------------\t\t\t-------\n");
            try
                threadExecutor.execute(withdrawal1);       
                threadExecutor.execute(deposit1);     
                threadExecutor.execute(withdrawal2);  
                threadExecutor.execute(deposit2);    
                threadExecutor.execute(withdrawal3);
                threadExecutor.execute(deposit3);       
                threadExecutor.execute(withdrawal4);
            catch ( Exception e )
                 e.printStackTrace();
                //shutdown worker threads
               threadExecutor.shutdown();
        }//end main
    }//end Assign2_Main/******************Withdrawal.java****************************/
    public class Withdrawal implements Runnable
    {//start  class Withdrawal
          *constructor
        public Withdrawal(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start ruin
             int newNum = 0;
                newNum = account.getBalance(name); 
               Thread.yield();
        }//end run
        private Account account;
        private String name;
    }//end  class Withdrawal/*******************Deposit.java***************/
    import java.util.Random;
    public class Deposit implements Runnable
    {//start class Deposit
          *constructor
        public Deposit(Account money, String n)
             account = money;
             name = n;
        public void run()
        {//start run
                try
                     Thread.sleep(100);
                   account.setBalance(random.nextInt(200), name);
                }// end try
                catch (InterruptedException e)
                  e.printStackTrace();
       }//end run
       private Account account;
       private Random random = new Random();
       private String name;
    }//end class Deposit/********************Account.java*****************/
    *Account interface specifies methods called by Producer and Consumer.
    public interface Account
         //place sum into Account
         public void setBalance(int sum, String name);
         //return  value of Account
            public int getBalance(String name);         
    } /**************SynchronizedThreads.java****************/
    import java.util.concurrent.locks.*;
    import java.util.Random;
    public class SynchronizedThreads implements Account
    {//start SynchronizedThreads
          *place money into buffer
        public void setBalance(int amount, String name)
        {//start setBalance
             // lock object
             myLock.lock();           
            sum += amount;
            System.out.println("\t\t\t\t" + name + " deposits $" + amount +"\t\t$"+ sum+"\n");       
               //threads are singnaled to wakeup
            MakeWD.signalAll();
              // unlock object                                                
            myLock.unlock();
           }//end setBalance
            *gets the balance from buffer
           public int getBalance(String name)
        {//start getBalance
             int NewSum = random.nextInt(50);
             //lock object
            myLock.lock();
            try
                 if(sum > NewSum)
                     //takes NewSum away from the account
                     sum -= NewSum;
                        System.out.println(name + " withdraws $" + NewSum +"\t\t\t\t\t\t$"+ sum+"\n");
                else
                     System.out.println(name +  " attempts $" + NewSum + " Withdrawal - Blocked - Insufficient Funds\n");                 
                     //not enough funds so thread waits
                        MakeWD.await();         
                //threads are singnaled to wakeup
                MakeD.signalAll();     
                }//end try
            catch (InterruptedException e)
                   e.printStackTrace();
            finally
                 //unlock object
                 myLock.unlock();
            return NewSum;     
         }//end getBalance
         private Random random = new Random();  
         private Lock myLock = new ReentrantLock();
         private Condition MakeD = myLock.newCondition();
         private Condition MakeWD = myLock.newCondition();
         private int sum = 0;
    }//end SynchronizedThreads

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • Problem with Thread and InputStream

    Hi,
    I am having a problem with threads and InputStreams. I have a class which
    extends Thread. I have created and started four instances of this class. But
    only one instance finishes its' work. When I check the state of other three
    threads their state remains Runnable.
    What I want to do is to open four InputStreams which are running in four
    threads, which reads from the same url.
    This is what I have written in my thread class's run method,
    public void run()
         URL url = new URL("http://localhost/test/myFile.exe");
    URLConnection conn = url.openConnection();
    InputStream istream = conn.getInputStream();
    System.out.println("input stream taken");
    If I close the input stream at the end of the run method, then other threads
    also works fine. But I do not want to close it becuase I have to read data
    from it later.
    The file(myFile.exe) I am trying to read is about 35 MB in size.
    When I try to read a file which is about 10 KB all the threads work well.
    Plz teach me how to solve this problem.
    I am using JDK 1.5 and Win XP home edition.
    Thanks in advance,
    Chamal.

    I dunno if we should be doing such things as this code does, but it works fine for me. All threads get completed.
    public class ThreadURL implements Runnable
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            try
                URL url = new URL("http://localhost:7777/java/install/");
                URLConnection conn = url.openConnection();
                InputStream istream = conn.getInputStream();
                System.out.println("input stream taken by "+Thread.currentThread().getName());
                istream.close();
                System.out.println("input stream closed by "+Thread.currentThread().getName());
            catch (MalformedURLException e)
                System.out.println(e);
                //TODO Handle exception.
            catch (IOException e)
                System.out.println(e);
                //TODO Handle exception.
        public static void main(String[] args)
            ThreadURL u = new ThreadURL();
            Thread t = new Thread(u,"1");
            Thread t1 = new Thread(u,"2");
            Thread t2 = new Thread(u,"3");
            Thread t3 = new Thread(u,"4");
            t.start();
            t1.start();
            t2.start();
            t3.start();
    }And this is the o/p i got
    input stream taken by 2
    input stream closed by 2
    input stream taken by 4
    input stream closed by 4
    input stream taken by 3
    input stream closed by 3
    input stream taken by 1
    input stream closed by 1
    can u paste your whole code ?
    ram.

  • How do you monitor a background thread and update the GUI

    Hello,
    I have a thread which makes its output available on PipedInputStreams. I should like to have other threads monitor the input streams and update a JTextArea embedded in a JScrollPane using the append() method.
    According to the Swing tutorial, the JTextArea must be updated on the Event Dispatch Thread. When I use SwingUtilities.invokeLater () to run my monitor threads, the component is not redrawn until the thread exits, so you don't see the progression. If I add a paint () method, the output is choppy and the scrollbar doesn't appear until the thread exits.
    Ironically, if I create and start new threads instead of using invokeLater(), I get the desired result.
    What is the correct architecture to accomplish my goal without violating Swing rules?
    Thanks,
    Brad
    Code follows:
    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SystemCommand implements Runnable
         private String[] command;
         private PipedOutputStream pipeout;
         private PipedOutputStream pipeerr;
         public SystemCommand ( String[] cmd )
              command = cmd;
              pipeout = null;
              pipeerr = null;
         public void run ()
              exec ();
         public void exec ()
              // --- Local class to redirect the process input stream to a piped output stream
              class OutputMonitor implements Runnable
                   InputStream is;
                   PipedOutputStream pout;
                   public OutputMonitor ( InputStream i, PipedOutputStream p )
                        is = i;
                        pout = p;
                   public void run ()
                        try
                             int inputChar;
                             for ( ;; )
                                  inputChar = is.read();
                                  if ( inputChar == -1 ) { break; }
                                  if ( pout == null )
                                       System.out.write ( inputChar );
                                  else
                                       pout.write ( inputChar );
                             if ( pout != null )
                                  pout.flush ();
                                  pout.close ();
                             else
                                  System.out.flush();
                        catch ( Exception e ) { e.printStackTrace (); }     
              try
                   Runtime r = Runtime.getRuntime ();
                   Process p = r.exec ( command );
                   OutputMonitor out = new OutputMonitor ( p.getInputStream (), pipeout );
                   OutputMonitor err = new OutputMonitor ( p.getErrorStream (), pipeerr );
                   Thread t1 = new Thread ( out );
                   Thread t2 = new Thread ( err );
                   t1.start ();
                   t2.start ();
                   //p.waitFor ();
              catch ( Exception e ) { e.printStackTrace (); }
         public PipedInputStream getInputStream () throws IOException
              pipeout = new PipedOutputStream ();
              return new PipedInputStream ( pipeout );
         public PipedInputStream getErrorStream () throws IOException
              pipeerr = new PipedOutputStream ();
              return new PipedInputStream ( pipeerr );
         public void execInThread ()
              Thread t = new Thread ( this );
              t.start ();
         public static JPanel getContentPane ( JTextArea ta )
              JPanel p = new JPanel ( new BorderLayout () );
              JPanel bottom = new JPanel ( new FlowLayout () );
              JButton button = new JButton ( "Exit" );
              button.addActionListener ( new ActionListener ( )
                                       public void actionPerformed ( ActionEvent e )
                                            System.exit ( 0 );
              bottom.add ( button );
              p.add ( new JScrollPane ( ta ), BorderLayout.CENTER );
              p.add ( bottom, BorderLayout.SOUTH );
              p.setPreferredSize ( new Dimension ( 640,480 ) );
              return p;
         public static void main ( String[] argv )
              // --- Local class to run on the event dispatch thread to update the Swing GUI
              class GuiUpdate implements Runnable
                   private PipedInputStream pin;
                   private PipedInputStream perr;
                   private JTextArea outputArea;
                   GuiUpdate ( JTextArea textArea, PipedInputStream in )
                        pin = in;
                        outputArea = textArea;
                   public void run ()
                        try
                             // --- Reads whole file before displaying...takes too long
                             //outputArea.read ( new InputStreamReader ( pin ), null );
                             BufferedReader r = new BufferedReader ( new InputStreamReader ( pin ) );
                             String line;
                             for ( ;; )
                                  line = r.readLine ();
                                  if ( line == null ) { break; }
                                  outputArea.append ( line + "\n" );
                                  // outputArea.paint ( outputArea.getGraphics());
                        catch ( Exception e ) { e.printStackTrace (); }
              // --- Create and realize the GUI
              JFrame f = new JFrame ( "Output Capture" );
              f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
              JTextArea textOutput = new JTextArea ();
              f.getContentPane().add ( getContentPane ( textOutput ) );
              f.pack();
              f.show ();
              // --- Start the command and capture the output in the scrollable text area
              try
                   // --- Create the command and setup the pipes
                   SystemCommand s = new SystemCommand ( argv );
                   PipedInputStream stdout_pipe = s.getInputStream ();
                   PipedInputStream stderr_pipe = s.getErrorStream ();
                   // --- Launch
                   s.execInThread ( );
                   //s.exec ();
                   // --- Watch the results
                   SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stdout_pipe ) );
                   SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stderr_pipe ) );
                   //Thread t1 = new Thread ( new GuiUpdate ( textOutput, stdout_pipe ) );
                   //Thread t2 = new Thread ( new GuiUpdate ( textOutput, stderr_pipe ) );
                   //t1.start ();
                   //t2.start ();
              catch ( Exception e ) { e.printStackTrace (); }
              

    Thanks for pointing out the SwingWorker class. I didn't use it directly, but the documentation gave me some ideas that helped.
    Instead of using invokeLater on the long-running pipe-reader object, I run it on a normal thread and let it consume the output from the background thread that is running the system command. Inside the reader thread I create a tiny Runnable object for each line that is read from the pipe, and queue that object with invokeLater (), then yield() the reader thread.
    Seems like a lot of runnable objects, but it works ok.

  • Threads and lockups

    Hi everyone,
    I have a question about threads. I have a JDesktopPane in a Frame. I have added a number of JInternalFrame to the JDeskTopPane that is show/hide as required. This all works fine.
    One particular internal frame is a frame that allows the training of a neural network. This process can take a long time so I am associated the neural network class with it's own thread and then calling "start()" (which runs the training sequence over the example set).
    During the traning sequence events are fired and are picked up by NeuralNetwork listeners. This is so that the progress of the neural network training can be monitorred. For example, my internal frame has a progress bar that increments every time a training cycle is completed (a training sequence consists on many training cycles).
    The problem occurs when the training sequence finishes. Somehoe things go haywire and my machine grinds to a halt. Everything slows down to a crawl and it is very difficult to get the machine to respond to anything.
    I believe that it is something to do with the way that I have defined by events. I have an event class defined as follows;
    /* CODE START */
    public class NeuralNetworkEvent extends java.util.EventObject {
        private int cycle = 0;
        public int getCycle() { return this.cycle; }
        public NeuralNetworkEvent(Object source, int cycle) {
            super(source);
            this.cycle = cycle;
    /* CODE END */
    And a listener defined like this;
    /* CODE START */
    public interface NeuralNetworkListener extends java.util.EventListener {
        public void trainingCycleCompleted(NeuralNetworkEvent evt);
    /* CODE END */
    Events are fired to registered listeners from within the neural network class like this;
    /* CODE START */
        public void addNeuralNetworkListener(NeuralNetworkListener listener) { neuralNetworkListeners.add(listener); }
        public void fireNeuralNetworkEvent() {
            for (int count = 0; count < neuralNetworkListeners.size(); count++)
                ((NeuralNetworkListener)neuralNetworkListeners.get(count)).trainingCycleCompleted(new NeuralNetworkEvent(this, currentCycle));
    /* CODE END */
    And my internal frame (which is a NeuralNetworkListener) does this when a neural network event is fired;
    /* CODE START */
        pbNetwork.setValue(pbNetwork.getValue() + 1);
        if ( evt.getCycle() == TOTAL_CYCLES - 1 ) cmdPredict.setEnabled(true);
    /* CODE END */
    Interestingly, execution never gets to the point where the predict button would be enabled (and I have checked the "if" statement for validity - it should resolve to "true"). In any case, is it at the point where the progress bar reaches 100% that everything goes haywire.
    I hope that someone can help me this this - I am a little stuck with this.
    Thanks in advance for you help. :)
    Ben

    Hi,
    Swing classes are not thread-safe. So if you want to update some Swing object (like the ProgressBar) from other than the Event Thread, use SwingUtilities.invokeLater(Runnable) or SwingUtilities.invokeAndWait(Runnable). Note, that firing an event takes place in the same Thread. So you might need to synchronize them as well.

  • Question about using threads and synchronizing objects

    Hi all,
    I am not that familiar and I have 2 questions.
    QUESTION 1
    I have a server which just sits and accepts incomming connections, then I spawn off a new thread which implements Runnable, and then call the run method. But the loop would not iterate, it would just sit inside the run method (which has rather long loop in it). I changed the class to extend Thread and called the start() method, rather than run(), and everything worked out fine.
    Anyone know why this is?
    QUESTION 2
    So I am building a client server chat application where a user can be in multiple chat rooms. I have this personObject which has output/input streams. In the personObject, I create writeObject/ readObject method, which simply does as it implies.
    I figured that I should make these methods synchronized, to ensure things run smoothly. however, when I made a call to readObject, which sat there and waited, and then made a call to writeObject, I would not enter the writeObject method. I took out the synchronized on the writeObject, and everything worked out fine.
    I was under the assumption that synchronizing a method only synchronized on that method, not on the whole class. How come then was I not able to enter the writeObject method?
    The more I think about it, I don't think I need to have these methods synchronized, but I thought it wouldn't hurt.
    Thanks for the help.

    Hi all,
    I am not that familiar and I have 2 questions.
    QUESTION 1
    I have a server which just sits and accepts incomming
    connections, then I spawn off a new thread which
    implements Runnable, and then call the run method.
    But the loop would not iterate, it would just sit
    inside the run method (which has rather long loop in
    it). I changed the class to extend Thread and called
    the start() method, rather than run(), and everything
    worked out fine.
    Anyone know why this is?
    You should still implement Runnable, rather than extending Thread. Like this: Runnable r = new MyRunnable();
    Thread t = new Thread(r);
    t.start(); run() is just another method. Nothing special about it as far as multithreading or anything else goes.
    start() is the method that actually spawns a new thread of execution.
    I was under the assumption that synchronizing a
    method only synchronized on that method, not on the
    whole class. How come then was I not able to enter
    the writeObject method?When you synchronize, you obtain a lock. As long as you hold that lock--until you exit the sync block or call wait()--no other thread can enter that block or any other block that obtains the same lock.
    Two synchronized methods on the same object rely on obtaining the same lock--there's one lock for each object.

  • About controllerUpdate and runnable

    Hello, i�m doing a program with video cameras. I have to see two cameras in a jpanel. Each camera has to be shown for some seconds. When the time of one camera finishes, the next camera must be displayed, and this action must be repited indefinitely.Each camera is thrown in a thread, and the conrtol of the time is done with runnable like this:
    miRunnable = new Runnable(){
                   public void run(){
                        try{
                             camera.wait(time);
                             stopCamera(camera[i]);
                             iniVisulizationCamera(comMV, pathC[j]);
                             i++;
                             Thread.currentThread().run();
              i = 0;
              hilo1 = new Thread (miRunnable);
              hilo1.start();
    The program show sthe first camera, next changes to the second one, next changes to the first camera another time, and it�s the las change. The runnable thread continues correctly running but controllerUpdate isn�t invoked. The controller only sends signals during around 30 seconds.
    My class RTP that implements controllerListener are:
    public class PanelVisualizadorRTP extends JPanel implements ReceiveStreamListener, ControllerListener {
    private int id;
    private boolean notify;
    private boolean hayVideo;
    private Visualizable client = null;
    private RTPManager mgr = null;
    private Player mplayer = null;
    public PanelVisualizadorRTP(int id, Visualizable client, boolean notify) {
    this.id = id;
    this.client = client;
    this.notify = notify;
    this.hayVideo = false;
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    setLayout(new BorderLayout());
    setPreferredSize(VisualizableSizes.SIZE_CIF);
    public void conectar(String senderIP, int lPort) throws IOException, InvalidSessionAddressException, UnknownHostException {
    mgr = RTPManager.newInstance();
    mgr.addReceiveStreamListener(this);
    SessionAddress sa = new SessionAddress(InetAddress.getLocalHost(), lPort);
    //mgr.initialize(new SessionAddress(InetAddress.getLocalHost(), lPort));
    mgr.initialize(sa);
    BufferControl bc = (BufferControl) mgr.getControl("javax.media.control.BufferControl");
    if (bc != null)
    bc.setBufferLength(BufferControl.MAX_VALUE);
    mgr.addTarget(new SessionAddress(InetAddress.getByName(senderIP), lPort));
    public synchronized void desconectar(String where) {
    System.out.println("[" + InstantTime.getTimestamp() + "] PanelVisualizadorRTP.desconectar{[id=" + id + "],[where=" + where + "]}");
    if (mgr != null) {
    if (mplayer != null && mplayer.getState() == Controller.Started) {
    mplayer.stop();
    mplayer.deallocate();
    mplayer = null;
    mgr.removeTargets("");
    mgr.dispose();
    mgr = null;
    * ReceiveStreamListener
    public synchronized void update(ReceiveStreamEvent evt) { 
    if (evt instanceof NewReceiveStreamEvent) {
    try {
    ReceiveStream stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    try {
    mplayer = javax.media.Manager.createPlayer(stream.getDataSource());
    mplayer.addControllerListener((ControllerListener) this);
    mplayer.realize();
    } catch (Exception e) {
    System.err.println("No se puede crear un player para el DataSource " + e.getMessage());
    } catch (Exception e) {
    System.err.println("NewReceiveStreamEvent excepci�n " + e.getMessage());
    return;
    } else if (evt instanceof InactiveReceiveStreamEvent) {
    desconectar("InactiveReceiveStreamEvent");
    } else if (evt instanceof TimeoutEvent) {
    desconectar("TimeoutEvent");
    } else if (evt instanceof ByeEvent) {
    desconectar("ByeEvent");
    * ControllerListener
    public synchronized void controllerUpdate(ControllerEvent ce) {
    if (ce instanceof RealizeCompleteEvent) {
    mplayer.start();
    } else if (ce instanceof StartEvent) {
    Component visual = mplayer.getVisualComponent();
    if (visual != null) {
    removeAll();
    add(visual, BorderLayout.CENTER);
    hayVideo = true;
    if (notify){
    client.startVisu(id);
    } else if (ce instanceof ControllerClosedEvent) {
    hayVideo = false;
    if (notify){
    client.stopVisu(id);
    } else if (ce instanceof ControllerErrorEvent) {
    desconectar("ControllerErrorEvent");
    If you have any idea of other coding...i would be very thank ful!

    Hello, i�m doing a program with video cameras. I have to see two cameras in a jpanel. Each camera has to be shown for some seconds. When the time of one camera finishes, the next camera must be displayed, and this action must be repited indefinitely.Each camera is thrown in a thread, and the conrtol of the time is done with runnable like this:
    miRunnable = new Runnable(){
    public void run(){
    try{
    camera.wait(time);
    stopCamera(camera);
    iniVisulizationCamera(comMV, pathC[j]);
    i++;
    Thread.currentThread().run();
    i = 0;
    hilo1 = new Thread (miRunnable);
    hilo1.start();
    }The program show sthe first camera, next changes to the second one, next changes to the first camera another time, and it�s the las change. The runnable thread continues correctly running but controllerUpdate isn�t invoked. The controller only sends signals during around 30 seconds.
    My class RTP that implements controllerListener are:
    public class PanelVisualizadorRTP extends JPanel implements ReceiveStreamListener, ControllerListener {
    private int id;
    private boolean notify;
    private boolean hayVideo;
    private Visualizable client = null;
    private RTPManager mgr = null;
    private Player mplayer = null;
    public PanelVisualizadorRTP(int id, Visualizable client, boolean notify) {
    this.id = id;
    this.client = client;
    this.notify = notify;
    this.hayVideo = false;
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    setLayout(new BorderLayout());
    setPreferredSize(VisualizableSizes.SIZE_CIF);
    public void conectar(String senderIP, int lPort) throws IOException, InvalidSessionAddressException, UnknownHostException {
    mgr = RTPManager.newInstance();
    mgr.addReceiveStreamListener(this);
    SessionAddress sa = new SessionAddress(InetAddress.getLocalHost(), lPort);
    //mgr.initialize(new SessionAddress(InetAddress.getLocalHost(), lPort));
    mgr.initialize(sa);
    BufferControl bc = (BufferControl) mgr.getControl("javax.media.control.BufferControl");
    if (bc != null)
    bc.setBufferLength(BufferControl.MAX_VALUE);
    mgr.addTarget(new SessionAddress(InetAddress.getByName(senderIP), lPort));
    public synchronized void desconectar(String where) {
    System.out.println("[" + InstantTime.getTimestamp() + "] PanelVisualizadorRTP.desconectar{[id=" + id + "],[where=" + where + "]}");
    if (mgr != null) {
    if (mplayer != null && mplayer.getState() == Controller.Started) {
    mplayer.stop();
    mplayer.deallocate();
    mplayer = null;
    mgr.removeTargets("");
    mgr.dispose();
    mgr = null;
    * ReceiveStreamListener
    public synchronized void update(ReceiveStreamEvent evt) {
    if (evt instanceof NewReceiveStreamEvent) {
    try {
    ReceiveStream stream = ((NewReceiveStreamEvent)evt).getReceiveStream();
    try {
    mplayer = javax.media.Manager.createPlayer(stream.getDataSource());
    mplayer.addControllerListener((ControllerListener) this);
    mplayer.realize();
    } catch (Exception e) {
    System.err.println("No se puede crear un player para el DataSource " + e.getMessage());
    } catch (Exception e) {
    System.err.println("NewReceiveStreamEvent excepci�n " + e.getMessage());
    return;
    } else if (evt instanceof InactiveReceiveStreamEvent) {
    desconectar("InactiveReceiveStreamEvent");
    } else if (evt instanceof TimeoutEvent) {
    desconectar("TimeoutEvent");
    } else if (evt instanceof ByeEvent) {
    desconectar("ByeEvent");
    * ControllerListener
    public synchronized void controllerUpdate(ControllerEvent ce) {
    if (ce instanceof RealizeCompleteEvent) {
    mplayer.start();
    } else if (ce instanceof StartEvent) {
    Component visual = mplayer.getVisualComponent();
    if (visual != null) {
    removeAll();
    add(visual, BorderLayout.CENTER);
    hayVideo = true;
    if (notify){
    client.startVisu(id);
    } else if (ce instanceof ControllerClosedEvent) {
    hayVideo = false;
    if (notify){
    client.stopVisu(id);
    } else if (ce instanceof ControllerErrorEvent) {
    desconectar("ControllerErrorEvent");
    }If you have any idea of other coding...i would be very thank ful!

  • Threads and progressbar

    hello all,
    I am trying to display a window with an indeterminate progress bar while I am searching through files looking for a particular file. The problem is that when I display the window, the outline of it appears, but never fully displays.......what I attempted to do, was make the window implement runnable. Inside of the run method, I set a JProgressbar to indeterminate and set the window to visible. Right before the code that searches for the file, I created a new thread and gave it an instance of my window class, then called the start method of the thread.
    ex
    class window extends JFrame implements runnable{
    JProgressbar bar = new......
    public void run(){
    bar.setIndeterminate(true);
    this.setVisible(true);
    inside of the main class(which itself is a JFrame)
    Thread temp;
    window mywindow = new window()
    temp = new Thread(mywindow);
    temp.start();
    //searching code here
    mywindow.dispose();
    anybody have any suggestions why the window doesn't display???
    Thanks

    Have you tried it without making the Progress window a thread? Just try opening the window and them starting the search. If that fails, try making the search a separate thread. I would avoid making the window a thread. The swing classes have their own threads running in the background. One thing I found that helps keep windows from freezing is when you have to fire a long process resulting from an actionPerformed event you can do this without writing a lot of code:
    //normal
    actionPerformed(ActionEvent e)
       doSomething();
    //allows window to refresh
    actionPerformed(ActionEvent e)
        new Thread() {
           public void run() {
                doSomething();
        }.start();
    }

  • Objects, Threads and Problems.

    Hi, im having an issue with multiple objects and multiple threads.
    Essentially, i have three different class, and ideally would like only one object of each. The problem is that i need to access each one from the other two, so i have to create a new object in each one. I tried using runnable, but then you can only put in 1 thread, and im going to be running a lot more.
    Can anyone help?
    thanks.

    Essentially, i have three different class, and
    ideally would like only one object of each. The
    problem is that i need to access each one from the
    other two, That sounds like a bad design, but ok.
    so i have to create a new object in each
    one. Why? This way you end up with an infinate amount of objects. Just keep references to each other.
    I tried using runnable, but then you can only
    put in 1 thread, and im going to be running a lot
    more.I don't understand how this is related?

  • Thread in runnable state

    I recently made my application from single threaded to multithreaded that sends emails after it gets details from DB about email address content etc.
    I primarily did this to send more mails concurrently. But I didn't see any performance improvement. After I took the stack trace couple of times I see all the threads are runnable but are not running. I understand JVM handles the switching of states, but I was wondering if I can go any further diagnosing what the problem is. It's a 2 CPU SunOS machine and I am spawning 3 threads.
    Stack Trace:
    1" prio=10 tid=0x0062cee8 nid=0x11 runnable [0xd347f000..0xd347fb70]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:313)
    - locked <0xd8c77cb0> (a java.io.BufferedInputStream)
    at com.informix.asf.IfxDataInputStream.readFully(IfxDataInputStream.java:149)
    at com.informix.asf.IfxDataInputStream.readSmallInt(IfxDataInputStream.java:428)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2177)
    at com.informix.jdbc.IfxSqli.sendStatementQuery(IfxSqli.java:1444)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1383)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1313)
    at com.informix.jdbc.IfxResultSet.executeQuery(IfxResultSet.java:216)
    at com.informix.jdbc.IfxStatement.executeQueryImpl(IfxStatement.java:839)
    at com.informix.jdbc.IfxPreparedStatement.executeQuery(IfxPreparedStatement.java:246)
    "0" prio=10 tid=0x0067ad18 nid=0x10 runnable [0xd357f000..0xd357faf0]
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(SocketInputStream.java:129)
    at java.io.BufferedInputStream.fill(BufferedInputStream.java:218)
    at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
    at java.io.BufferedInputStream.read(BufferedInputStream.java:313)
    - locked <0xd8caa908> (a java.io.BufferedInputStream)
    at com.informix.asf.IfxDataInputStream.readFully(IfxDataInputStream.java:149)
    at com.informix.asf.IfxDataInputStream.readSmallInt(IfxDataInputStream.java:428)
    at com.informix.jdbc.IfxSqli.receiveMessage(IfxSqli.java:2177)
    at com.informix.jdbc.IfxSqli.sendStatementQuery(IfxSqli.java:1444)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1383)
    at com.informix.jdbc.IfxSqli.executeStatementQuery(IfxSqli.java:1313)
    at com.informix.jdbc.IfxResultSet.executeQuery(IfxResultSet.java:216)
    at com.informix.jdbc.IfxStatement.executeQueryImpl(IfxStatement.java:839)
    at com.informix.jdbc.IfxPreparedStatement.executeQuery

    java.io is a blocking protocol.
    If you want to see improved performance you at least need to use java.nio.
    Even so, just allocating more threads will not make your program run faster.
    Unless your code can inherently use multiple-cpus, multiple threads will do you no good at all.
    Threads are useful for four things :
    1. Making people (or some other connected system) '*think*' you are doing multiple things at the same time, of course you are not doing so, the scheduler is just slicing up the cpu time and giving some to each thread. This is essentially "servicing a request within some acceptable amount of time", which is why you see a lot of thread usage on web servers.
    2. If you have a piece of code that can usefully divide work between two or more CPUs then threads can help you, even so allocating more threads than you have CPUs will not help, in fact your program will probably slow down (unless the threads are not doing anything at all.)
    3. The implementation of some algorithms can be easier to think about as a set of communicating processes, in which case you can use threads to achieve an implementation.
    4. Simulation : if you are simulating the interaction of objects in a complex system it can be useful to use threads in the simulation, but it does not necessarily run any faster, you are just using threads to help model the system.
    Most programs/programmers will be in category #1, as more multi-core / multi-cpu machine are deployed there will be pressure to move to category #2, but I think most people have a lot to learn about this subject.
    When attempting to achieve higher performance by using a mult-cpu machine, you need to think about how you define performance.
    It is better to measure "how much work" gets done in a fixed amount of time rather than measuring "how fast" your program is running, i.e. how much faster it executes a specific task.

  • Example of WAIT and CONTINUE using checkBox and thread and getTreeLock()

    I had so much trouble with this that I descided to
    post if incase it helps someone else
    // Swing Applet example of WAIT and CONTINUE using checkBox and thread and getTreeLock()
    // Runs form dos window
    // When START button is pressed program increments x and displys it as a JLabel
    // When checkBox WAIT is ticked program waits.
    // When checkBox WAIT is unticked program continues.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    public class Wc extends JApplet {
    Display canvas;//drawing surface is displayed.
    Box buttonPanel;
    Box msgArea;
    public static JButton button[] = new JButton [2];
    public static JCheckBox checkBox[] = new JCheckBox[2];
    public static JLabel msg[] = new JLabel [2];
    String[] buttonDesc ={"Start","Quit"};
    public static final int buttonStart = 0;
    public static final int buttonQuit = 1;
    String[] checkBoxDesc ={"Wait"};     
    public static final int checkBoxWait = 0;
    public boolean wait;
    public Graphics g;
    //================================================================
    public static void main(String[] args){
    Frame f = new Frame();
    JApplet a = new Wc();
    f.add(a, "Center"); // Add applet to window
    a.init(); // Initialize the applet
    f.setSize(300,100); // Set the size of the window
    f.show(); // Make the window visible
    f.addWindowListener(
    new WindowAdapter(){
    public void windowClosing(WindowEvent e){System.exit(0);}
    }// end main
    //===================================================
    public void init() {
    canvas = new Display();
    setBackground(Color.black);
    getContentPane().setLayout(new BorderLayout(3,3));
    getContentPane().add(canvas, BorderLayout.CENTER);
    buttonPanel = Box.createHorizontalBox();
    getContentPane().add(buttonPanel, BorderLayout.NORTH);
    int sbZ;
    // add button
    button[0] = new JButton(buttonDesc[0]);
    button[0].addActionListener(canvas);
    buttonPanel.add(button[0]);
    button[1] = new JButton(buttonDesc[1]);
    button[1].addActionListener(canvas);
    buttonPanel.add(button[1]);
    // add checkBox
    sbZ=0;
    checkBox[sbZ]=new JCheckBox(checkBoxDesc[sbZ]);
    checkBox[sbZ].setBackground(Color.white);
    checkBox[sbZ].setOpaque(true);
    checkBox[sbZ].addActionListener(canvas);
    buttonPanel.add(checkBox[sbZ]);
    msgArea = Box.createVerticalBox(); // add message
    sbZ=0;
    msg[sbZ]=new JLabel("1",JLabel.LEFT);
    msg[sbZ].setOpaque(true);
    msg[sbZ].setBackground(Color.black);
    msg[sbZ].setForeground(Color.red);
    msgArea.add(msg[sbZ]);
    getContentPane().add(msgArea, BorderLayout.SOUTH);
    } // end init();
    //===================================================
    public void stop(){canvas.stopRunning();}
    //===================================================
    // The following nested class represents the drawing surface
    // of the applet and also does all the work.
    class Display extends JPanel implements ActionListener, Runnable {
    Image OSI;
    Graphics OSG; // A graphics context for drawing on OSI.
    Thread runner; // A thread to do the computation.
    boolean running; // Set to true when the thread is running.
    public void paintComponent(Graphics g) {
    if (OSI == null) {
    g.setColor(Color.black);
    g.fillRect(0,0,getWidth(),getHeight());
    else {g.drawImage(OSI,0,0,null);}
    }//paintComponent
    public void actionPerformed(ActionEvent evt) {
    String command = evt.getActionCommand();
    if (command.equals(buttonDesc[buttonStart])) {
    startRunning();
    if (command.equals(buttonDesc[buttonQuit])) {
    stopRunning();
    if (command.equals(checkBoxDesc[checkBoxWait])){
    System.out.println("cb");
    if (checkBox[checkBoxWait].isSelected() ) {
    wait = true;
    System.out.println("cb selected twait "+wait);
    return;
    wait = false;
    synchronized(getTreeLock()) {getTreeLock().notifyAll();}
    System.out.println("cb selected fwait "+wait);
    } // end command.equal cb wait
    } //end action performed
    // A method that starts the thread unless it is already running.
    void startRunning() {
    if (running)return;
    // Create a thread that will execute run() in this Display class.
    runner = new Thread(this);
    running = true;
    runner.start();
    } //end startRunning
    void stopRunning() {running = false;System.exit(0);}
    public void run() {
    button[buttonStart].setEnabled(false);
    int x;
    x=1;
    while(x>0 && running){
    x = x + 1;
    msg[0].setText(""+x);
    try{SwingUtilities.invokeAndWait(painter);}catch(Exception e){}
    //importand dont put this in actionPerformed
    if (wait) {
    System.out.println("run "+wait);
    synchronized(getTreeLock()) {
    while(wait) {
    System.out.println("while "+wait);
    try {getTreeLock().wait();} catch(Exception e){break;}
    } //end while(wait)
    } // end sync
    } // end if(wait)
    } // endwhile(x>0)
    stopRunning();
    } // end run()
    Runnable painter = new Runnable() {
    public void run() {
    Dimension dim = msg[0].getSize();
    msg[0].paintImmediately(0,0,dim.width,dim.height);
    Thread.yield();
    }//end run in painter
    } ; //end painter
    } //end nested class Display
    } //end class Wc

    I just encountered a similar issue.  I bought a new iPhone5s and sent my iPhone4s for recycling as it was in great shape, no scratches, no breaks, perfect condition.  I expected $200 and received an email that I would only receive $24.12.  The explanation was as follows:  Phone does not power on - Power Supply Error.   Attempts to discuss don't seem to get past a customer service rep that can only "escalate" my concern.  They said I would receive a response, but by email.  After 4 days no response.  There is something seriously wrong with the technical ability of those in the recycling center.

  • SwingEvent thread and synchronization

    I am having a problem where my app keeps locking up. I have a swing application that receives asynchronous realtime messages from a server.
    On receiving these messages my views are required to update the components. I do this my calling a method with a synchronized block that updates the views components in a SwingUtilities.invokeLater clause.
    This seems to work fine. However, sometimes when I click a menu item/button the app locks up.
    I have put some debug in that shows me the synchronized block started but did not complete?!?!
    I think this tells me that the SwingEvent thread interrupted my external notification thread, and caused some sort of deadlock.
    If this is the case then why does my synchronized block of code not complete. I am not altogether sure what I should synchronize around.
    For example I am doing something like this>
    public void notify(Model model){
    if(model == null) return;
    synchronized(model){
    System.out.println("started");
    SwingUtilities.invokeLater(new Runnable(){
    componentA.setText(model.getName());
    System.out.println("ended");
    My output when it locks is like this
    started
    ended
    started
    ended
    started
    At this point the app is frozen.
    So I guess what I am asking is as follows>
    Is the SwingEvent thread interrupting my external notification thread?
    If so, why is the synchronized block not completing.
    What should I synchronize?
    Any help would be greatly appreciated.
    Dr Nes

    If there is a deadlock (which seems likley), and you are running on jdk 1.4.x, you simply have to do Ctrl-Break (on windows) or crtl-\ (on unix) to get the complete state of all threads and and lock objects. From this it should be fairly simple to figure out what is causing the problem.

Maybe you are looking for