Stopping a Runnable

Hi!
I want to stop a class that implements the Runnable interface. I thought that this will be the way to do it:
I override the run() method like this:
public void run() {
   while(booleanFlag) {
      // do stuffs here
}     And I start the thread like this:
MyRunnable mR = new MyRunnable ();
Thread t= new Thread(mR);
t.start();Then when I want to stop that thread, simply make the booleanFlag to false.
I read the Java "Why Are Thread.stop ... Deprecated?", but theres nothing about Runnable. And I searched this forum topic, but it is too huge to find the answer.

Never mind Thread#stop() - your approach of stopping the runnable is correct and will cause the thread to terminate properly.
JavaDoc
Many uses of stop should be replaced by code that simply modifies some variable to
indicate that the target thread should stop running. The target thread should check this
variable regularly, and return from its run method in an orderly fashion if the variable
indicates that it is to stop running.However, you'll have to make sure that your flag is declared volatile. If you do not add the volatile flag, your thread may actually access a cached version of the running state and not react to another thread changing the field.

Similar Messages

  • How do you stop a runnable

    Hi,
    it say that stop() is deprecated. I also try distroy() and it is not implemeneted by design. so how do you kill a runnable??

    First of all a Runnable has only one method run();
    So you have to call methods on the thread created with the
    Runnable.
    Try using the interrupt(); method
    then the run loop in the run method should look
    like this
    public void run()
    while(!interrupted())
    // put code here

  • The problem of thread pool

    I want to make a thread pool to handle UDP package request
    so I set tow int variable :
    norsize;
    maxsize;
    the norsize is normal amount threads when Server boot they will be creat;
    the maxsize is when the quest is large and the norsize threads are not enough,The
    Thead pool can increase to the amount
    but how reduce the Thread pool amount when it reach the maxsize????

    That was funy (the Duke Dollars part) :)
    Ok. This time with some code.
    We have a class that manages work. This work is made up of Runnable objects and the threads that run it. Let's go with sample code instead of english, just remenber that I wrote this code directly to the post text area and didn't event compile it, although it should work.
    publi class WorkQueue {
        private LinkedList m_listRunnable;
        private int m_nMinThread;
        private int m_nMaxThread;
        private int m_nTimeOut;
        private int m_nNumThread;
        private int m_nNumThreadWaiting;
        public WorkQueue(int minThread, int maxThread, int timeOut) {
            m_listRunnable = new LinkedList();
            m_nMinThread = minThread;
            m_nMaxThread = maxThread;
            m_nTimeOut = timeOut;
            m_nNumThread = 0;
            m_nNumThreadWaiting = 0;
            init();
        private void init() {
            /* Start MinThread threads */
            for (i = 0; i < m_nMinThread; i++) {
                 new WorkSlaveThread();
                 m_nNumThread++;
        /* Inner class for the work thread */
        private class WorkSlaveThread extends Thread {
            public WorkSlaveThread() {
            public void run() {
                /* Work unless no work is returned, then it should stop */
                for (Runnable work = getNextWork(); work != null; work = getNextWork()) {
                    try {
                        work.run();
                    } catch (Throwable ex) {
                        /* Log the error */
                        ex.printStackTrace();
                threadStopping();
        private void threadStopping() {
            synchronized (this) {
                m_nNumThread--;
        private Runnable getNextWork() {
            Runnable work;
            long starttime = System.currentTimeMillis();
            long currenttime = starttime;
            long timeOut = m_nTimeOut * 1000; // Assume the time on in the constructor is in seconds
            synchronized (m_listRunnable) {
                /* Until there is work and the time out hasn't exceed */
                /* (time out ignored if the minimum umber of threads is reached) */
                while ((m_listRunnable.size() == 0) && ((timeOut > (currenttime - starttime)) || (m_nThreads == m_nMinThreads))) {
                    try {
                        m_nNumThreadWaiting++;
                        m_listRunnable.wait(m_nTimeOut * 1000);
                    } catch (Exception ex) {
                        /* Exception are launched if the VM is going down */
                        return null;
                    } finally {
                        m_nNumThreadWaiting--;
                    currenttime = System.currentTimeMillis();
                if (m_listRunnable.size () == 0) {
                    /* Stop threads procedure */
                    return null; // Null will stop the thread
                } else {
                    work = (Runnable)m_listRunnable.remove(0);
                    return work;
        public void addWork(Runnable work) {
            synchronized (m_listRunnable) {
                m_listRunnable.add(work);
                /* Start threads if necessary */
                if ((m_nNumThreadWaiting == 0) && (m_nNumThread < m_nMaxthread)) {
                    new WorkSlaveThread();
                    synchronized (this) {
                        m_nNumThread++;
                /* Signal a waiting thread */
                m_listRunnable.notify();
    }Well, this about does it! I didn't compile this, nor this is the code I use internally (internally I have shutdown procedures to ensure all work is down and other things), but it should do all the things a mention previously (I don't think I forgot any thing).
    Hope this helps,
    Nuno

  • Problems with a simple stop watch program

    I would appreciate help sorting out a problem with a simple stop watch program. The problem is that it throws up inappropriate values. For example, the first time I ran it today it showed the best time at 19 seconds before the actual time had reached 2 seconds. I restarted the program and it ran correctly until about the thirtieth time I started it again when it was going okay until the display suddenly changed to something like '-50:31:30:50-'. I don't have screenshot because I had twenty thirteen year olds suddenly yelling at me that it was wrong. I clicked 'Stop' and then 'Start' again and it ran correctly.
    I have posted the whole code (minus the GUI section) because I want you to see that the program is very, very simple. I can't see where it could go wrong. I would appreciate any hints.
    public class StopWatch extends javax.swing.JFrame implements Runnable {
        int startTime, stopTime, totalTime, bestTime;
        private volatile Thread myThread = null;
        /** Creates new form StopWatch */
        public StopWatch() {
         startTime = 0;
         stopTime = 0;
         totalTime = 0;
         bestTime = 0;
         initComponents();
        public void run() {
         Thread thisThread = Thread.currentThread();
         while(myThread == thisThread) {
             try {
              Thread.sleep(100);
              getEnd();
             } catch (InterruptedException e) {}
        public void start() {
         if(myThread == null) {
             myThread = new Thread(this);
             myThread.start();
        public void getStart() {
         Calendar now = Calendar.getInstance();
         startTime = (now.get(Calendar.MINUTE) * 60) + now.get(Calendar.SECOND);
        public void getEnd() {
         Calendar now1 = Calendar.getInstance();
         stopTime = (now1.get(Calendar.MINUTE) * 60) + now1.get(Calendar.SECOND);
         totalTime = stopTime - startTime;
         setLabel();
         if(bestTime < totalTime) bestTime = totalTime;
        public void setLabel() {
         if((totalTime % 60) < 10) {
             jLabel1.setText(""+totalTime/60+ ":0"+(totalTime % 60));
         } else {
             jLabel1.setText(""+totalTime/60 + ":"+(totalTime % 60));
         if((bestTime % 60) < 10) {
             jLabel3.setText(""+bestTime/60+ ":0"+(bestTime % 60));
         } else {
             jLabel3.setText(""+bestTime/60 + ":"+(bestTime % 60));
        private void ButtonClicked(java.awt.event.ActionEvent evt) {                              
         JButton temp = (JButton) evt.getSource();
         if(temp.equals(jButton1)) {
             start();
             getStart();
         if(temp.equals(jButton2)) {
             getEnd();
             myThread = null;
         * @param args the command line arguments
        public static void main(String args[]) {
         java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
              new StopWatch().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                  
    }

    Although I appreciate this information, it still doesn't actually solve the problem. I can't see an error in the logic (or the code). The fact that the formatting works most of the time suggests that the problem does not lie there. As well, I use the same basic code for other time related displays e.g. countdown timers where the user sets a maximum time and the computer stops when zero is reached. I haven't had an error is these programs.
    For me, it is such a simple program and the room for errors seem small. I am guessing that I have misunderstood something about dates, but I obviously don't know.
    Again, thank you for taking the time to look at the problem and post a reply.

  • How can i stop the screen from flickering in this program?

    Hi, i just wanted to know if anybody knows why my screen keeps flickering when i move.
    * @(#)CarWKeys.java
    * CarWKeys Applet application
    * @author
    * @version 1.00 2008/11/29
    import java.awt.*;
    import java.applet.*;
    import java.awt.image.*;
    public class CarWKeys extends Applet implements Runnable
          private Image dbImage;
         private Graphics dbg;
          Image img,CarWKeys1,cup;
          // This Field is to Trace out the User's CarWKeys position
          static int position=235;
          static int points = 0;
          // You can change this delay to any value which effects in the speed of the game
          static int delay = 100;
          road rd;
          Thread thr;
          static int pts=50;
          boolean msg=true;
          // If this field is true then the 'road' thread will be stopped
          static boolean kill=false;
          public void init()
         int x[] = { 15, 15, 0, 60, 45, 45 };
         int y[] = { 45, 50, 58, 58, 50, 45 };
         setBackground(Color.black);
                // Drawing the CarWKeys Image
                img = createImage(60,60);
                Graphics g = img.getGraphics();
                g.setColor(Color.black);
                g.fillRect(0,0,60,60);
                g.setColor(Color.green);
                g.fillRect(12,20,36,7);
                g.fillRect(8,15,4,17);
                g.fillRect(48,15,4,17);
                g.fillRect(5,40,50,7);
                g.fillRect(0,35,5,17);
                g.fillRect(55,35,5,17);
                g.setColor(Color.red);
                g.fillRect(20,0,20,15);
                g.fillRect(15,15,30,40);
                g.setColor(Color.blue);
                g.fillRect(20,20,7,10);
                g.fillRect(33,20,7,10);
                g.setColor(Color.red);
                g.fillRect(22,22,3,6);
                g.fillRect(35,22,3,6);
                g.setFont(new Font("TimesRoman",Font.PLAIN,7));
                g.setColor(Color.white);
                g.fillPolygon(x,y,6);
                g.setColor(Color.black);
                g.drawString("YAMAHA",15,52);
                // Drawing the CarWKeys Image
                CarWKeys1 = createImage(60,60);
                Graphics g1 = CarWKeys1.getGraphics();
                g1.setColor(Color.black);
                g1.fillRect(0,0,60,60);
                g1.setColor(Color.green);
                g1.fillRect(12,20,36,7);
                g1.fillRect(8,15,4,17);
                g1.fillRect(48,15,4,17);
                g1.fillRect(5,40,50,7);
                g1.fillRect(0,35,5,17);
                g1.fillRect(55,35,5,17);
                g1.setColor(Color.blue);
                g1.fillRect(20,0,20,15);
                g1.fillRect(15,15,30,40);
                g1.setColor(Color.red);
                g1.fillRect(20,20,7,10);
                g1.fillRect(33,20,7,10);
                g1.setColor(Color.blue);
                g1.fillRect(22,22,3,6);
                g1.fillRect(35,22,3,6);
                g1.setFont(new Font("TimesRoman",Font.PLAIN,7));
                g1.setColor(Color.white);
                g1.fillPolygon(x,y,6);
                g1.setColor(Color.black);
                g1.drawString(" B.M.W ",15,52);
                thr = new Thread(this); thr.start(); rd = new road(getGraphics(),CarWKeys1,this); rd.start();
                // Cup Image
                int a[] = {20,5,35};
                int b[] = {150,160,160};
                cup = createImage(50,165);
                Graphics handle = cup.getGraphics();
                handle.setColor(Color.black);
                handle.fillRect(0,0,50,165);
                handle.setColor(Color.red);
                handle.fillArc(0,40,40,30,0,180);
                handle.setColor(Color.yellow);
                handle.fillArc(0,15,40,80,180,180);
                handle.setColor(Color.red);
                handle.drawLine(20,95,20,150);
                handle.fillPolygon(a,b,3);
          public void update (Graphics g)
              // DoubleBuffers
              if (dbImage == null)
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (getForeground());
              paint (dbg);
              g.drawImage (dbImage, 0, 0, this);
          public void run()
                // If you cross the 50 mark you will get a Cup of Java
                while(points <= 15)
             if(points == 50 || kill == true)
             rd.stop();
             repaint();
             thr.stop();
             if((points%4)==0)
               rd.j = 0;
               pts = points;
                points++;
                            delay--;
                            if(delay <= 0)
                                  delay = 0;
                            rd.flag=1;
                            repaint();
                      try
                            Thread.sleep(delay);
                      }catch(InterruptedException exp){}
          public void destroy()
                thr.stop();
                rd.stop();
          //If User presses mouse the the CarWKeys is shifted to opposite side of the road
               public boolean keyDown(Event evt, int key) {
        if (key==Event.LEFT){
        // left arrow key pressed
        if(position == 355)
           position = 235;
        else if(key== Event.RIGHT){
        // right arrow key pressed
        if(position == 235)
           position = 355;
       repaint();
      return true;
          public void paint(Graphics gr)
                if(!kill)
                      if(msg)
                            // This is the opening message
                    gr.setColor(Color.black);
                    gr.fillRect(0,0,640,400);
                            gr.setColor(Color.yellow);
                            gr.setFont(new Font("TimesRoman",Font.BOLD,16));
                            gr.drawString("TO START THE GAME CLICK THE SCREEN",140,100);
                            gr.drawString("USE THE ARROW KEYS TO MOVE THE CAR",140,200);
                            gr.drawString("WAIT A MINUTE......",230,240);
                            msg = false;
                            try{
                                  Thread.sleep(3000);
                            }catch(Exception exp){}
                            gr.setColor(Color.black);
                            gr.fillRect(0,0,640,400);
                      gr.setColor(Color.white);
                      gr.fillRect(200,0,10,400);
                      gr.fillRect(440,0,10,400);
                      gr.drawImage(img,position,300,this);
                      gr.setColor(Color.yellow);
                      gr.fillRect(550,5,637,25);
                      gr.setColor(Color.blue);
                      gr.setFont(new Font("TimesRoman",Font.BOLD,20));
                      gr.drawString("Score :"+pts,557,22);
                      if(points >= 16)
                            for(int xyz=0;xyz<3;xyz++)
                                  gr.setColor(Color.yellow);
                                  gr.drawString("Have a Cuppa Java",240,100);
                                  gr.drawImage(cup,300,100,this);
                                  gr.setColor(Color.yellow);
                                  gr.fillRect(550,5,637,25);
                                  gr.setColor(Color.blue);
                                  gr.setFont(new Font("TimesRoman",Font.BOLD,20));
                                  gr.drawString("Score :50",557,22);
                                  try
                                        Thread.sleep(500);
                                  }catch(InterruptedException exp){}
                else
                      gr.setColor(Color.yellow);
                      gr.drawString("YOU HAVE LOST THE GAME",250,200);
    class road extends Thread
          int i;
          public static int j = 0;
          Graphics g;
          Image CarWKeys2;
          ImageObserver io;
          public static int flag = 0;
          boolean msg=true;
          road(Graphics g,Image CarWKeys2,ImageObserver io)
                this.g = g;
                this.io = io;
                this.CarWKeys2 = CarWKeys2;
          public void run()
                drawRoad(g);
          // The actual logic i.e Moving of CarWKeyss is here
          public void drawRoad(Graphics gr)
                if(msg)
                      gr.setColor(Color.black);
                      gr.fillRect(0,0,640,400);
                      gr.setColor(Color.yellow);
                      gr.setFont(new Font("TimesRoman",Font.BOLD,16));
                            gr.drawString("TO START THE GAME CLICK THE SCREEN",140,100);
                            gr.drawString("USE THE ARROW KEYS TO MOVE THE CAR",140,200);
                            gr.drawString("WAIT A MINUTE......",230,240);
                      msg = false;
                      try
                            Thread.sleep(3000);
                      }catch(Exception exp){}
                      gr.setColor(Color.black);
                      gr.fillRect(0,0,640,400);
                for(;j<=1000;j+=10)
                      for(i=-1000;i<=479;i+=60)
                            gr.setColor(Color.black);
                            gr.fillRect(320,i+j,10,i+j+50);
                            gr.setColor(Color.white);
                            gr.fillRect(320,i+j+10,10,i+j+60);
                      gr.clearRect(235,j-10,60,60);
                      gr.drawImage(CarWKeys2,235,0+j,io);
                      gr.clearRect(355,-150+(j-10),60,60);
                      gr.drawImage(CarWKeys2,355,-150+j,io);
                      gr.clearRect(235,-300+(j-10),60,60);
                      gr.drawImage(CarWKeys2,235,-300+j,io);
                      gr.clearRect(355,-450+(j-10),60,60);
                      gr.drawImage(CarWKeys2,355,-450+j,io);
                      if( (CarWKeys.position == 235 && (j >= 250 && j <= 360)) || (CarWKeys.position == 355 && (j >= 400 && j <= 510)) || (CarWKeys.position == 235 && (j >= 550 && j <= 660)) || (CarWKeys.position == 355 && (j >= 700 && j <= 810)) )
                            try
                                  Thread.sleep(2000);
                                  CarWKeys.kill = true;
                            }catch(InterruptedException exp){}
                      if (j >= 360 ) { if( (( j - 360 ) % 150 ) == 0 )
                            if(flag == 1)
                                  CarWKeys.points--;
                                  flag = 0;
                            CarWKeys.points++;
                            gr.setColor(Color.yellow);
                            gr.fillRect(550,5,637,25);
                            gr.setColor(Color.blue);
                            gr.setFont(new Font("TimesRoman",Font.BOLD,20));
                            gr.drawString("Score :"+CarWKeys.points,557,22);
                try
                      Thread.sleep(CarWKeys.delay);
                }catch(InterruptedException exp){}
    }

    Look at the link I posted, you aren't double buffering correctly.
    I saw the other post you mistakenly made before you edited it. Not really a big deal, I was just wondering why you did that.

  • Stop scroll bar in JScrollPane from updating viewport when dragging knob

    Hi,
    Does anyone know if it's possible to stop the JScrollPane from updating the viewport whilst dragging the knob of the scrollbar and only update once released.
    The problem I have is that the view of the scroll panes viewport is a JList that has an underlying model of a RandomAccessFile which can be very large. So when the user is dragging the scrollbars it will be accessing the file system to retrieve the relevant data for the JList.
    I've tried creating my own JScrollBar and adding a AdjustmentListener to ignore events whilst dragging:
    class MyAdjustmentListener implements AdjustmentListener {
    // This method is called whenever the value of a scrollbar is changed,
    // either by the user or programmatically.
    public void adjustmentValueChanged(AdjustmentEvent evt) {
    Adjustable source = evt.getAdjustable();
    // getValueIsAdjusting() returns true if the user is currently
    // dragging the scrollbar's knob and has not picked a final value
    if (evt.getValueIsAdjusting()) {
    // The user is dragging the knob
    return;
    Looking through the JScrollBar code it has a model that will fire adjustment events anyway, which I suppose are being picked up by the JScrollPane somewhere.
    I could use my own JScrollBar and not add it to the scroll pane and process the adjustment events myself and update the JList but I was wondering if there is a better way.
    Many Thanks,
    Martin.

    Two small changes seem to do the trick. You may want to test it thoroughly though ;)import javax.swing.BoundedRangeModel;
    import javax.swing.DefaultBoundedRangeModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class OneStepScroller {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new OneStepScroller().makeUI();
       public void makeUI() {
          Object[] data = new Object[200];
          for (int i = 0; i < data.length; i++) {
             data[i] = "Item Number " + i;
          JList list = new JList(data);
          JScrollPane scrollPane = new JScrollPane(list);
          BoundedRangeModel model = scrollPane.getVerticalScrollBar().getModel();
          final JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
          scrollBar.setModel(new DefaultBoundedRangeModel(model.getValue(),
                model.getExtent(), model.getMinimum(), model.getMaximum()) {
             int oldValue;
             @Override
             public int getValue() {
                // changed here
                if (!getValueIsAdjusting() && !(oldValue == super.getValue())) {
                   oldValue = super.getValue();
                   // added this
                   fireStateChanged();
                return oldValue;
          JFrame frame = new JFrame("");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 400);
          frame.setLocationRelativeTo(null);
          frame.add(scrollPane);
          frame.setVisible(true);
    }db

  • Stopping a Thread in Infinite Loop

    I've read several articles on how to stop Threads, and all of them point to using Thread.interrupt(). The problem right now is what happens when the thread is in an infinite loop. For example:
    class A implements Runnable
        public void run()
            while(!Thread.currentThread().isInterrupted())
                  while(true);
    //in other class's main method:
    Thread a = new Thread(new A());
    a.start();
    a.interrupt();The a.interrupt() call only sets the isInterrupted flag in Thread, but it does not terminate the thread as a.stop() would. However, stop() throws a ThreadDeath exception that I would not want to have to deal with. Is there any way to stop this infinite loop thread safely?
    Thanks in advance!

    No need to get snitty. You certainly did not make clear that you are not a newbie at programming. Plenty of newbies who barely have a grasp of the language fundamentals post thread questions here. I thought I did address the question at hand. It seems I misunderstood what you were asking.
    The only way to safely stop that inner loop is like so: while (...) {
       while (!done) {
    }where done is volatile, or all access to it is sychronized on the same lock (meaning you'd sync the !done check above as well).
    If you can't do that, and it's stuck at while (true) and you can't modify the body of the inner loop to check done, then you're SOL.
    (I suppose it's conceivable that 1.6 or 6.0 or whatever it's called will introduce some new safe way to stop that thread, but I haven't heard anything about it.)

  • How to stop while loop for particular time

                    public void test()
                   new Thread(new Runnable()
                        public void run()
                             //Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
                             System.out.println("test");
                             //System.out.println("test ..."+i);
                             try
                                  Thread.sleep(3000);
                             catch (InterruptedException e)
                   }).start();
            public void startTest()
                    while(i < marquee_Str1.length)
                   marLbl1.setValue(marquee_Str1); //set value to textbox for perticular id
                   marLbl2.setValue(marquee_Str2[i]);
                   marLbl3.setValue(marquee_Str3[i]);
                   test(); // call thread function
                   i++;
    in this code while loop don't stop
    plz help me to stop while loop for certain period by using thread or other technique                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Yes.. the original problem would be your test() method put the sleep in an entirely separate thread of execution. So the thread is created then the method just keeps waiting. The while loop should directly call Thread.sleep... which you have apparently figured out!

  • Stop a socket listening thread?

    Hi all,
    I'm a newbie at java socket programming, and i have a problem in implementing realibility over UDP.
    This is the pseudocode of my program.
    class ChatProtocol
         DatagramSocket socket;
         Thread alwaysListeningSocket;
         public ChatProtocol(parameter)
              // Some setting up
    ]          this.alwaysListeningSocket = this;
         public void run()
              DatagramPacket packet = new DatagramPacket(parameter);
              socket.receive(packet);
              .     // Process the incoming messages
         public void send(message)
              // Chunking the message into datagramPackets[]
              // Thread for listening for acknowledgement for each will-be-sent packets
              Thread ackListener = new Thread(new Runnable()
                   public void run()
                        DatagramPacket ackPacket = new DatagramPacket(parameter);
                        socket.receive(ackPacket);
                        .     // Processing the acknowledgement
              ackListener.start(); // Start listening for ack
              for (int i = 0; i < datagramPackets.length; i++)
                   socket.send( datagramPacktes[i] );
              .     // Another process
    }I have an always listening socket in my program, which is done by invoking socket.receive() inside a thread
    And i have a send method, which will send messages thorugh the same socket.
    The problem is, i have to listen for acknowledgement for each sent packets through the same socket.
    This is done by invoking socket.receive(), but if i want to invoke this method, i have to stop the previous thread first.
    Is this possible, since stop() method in Thread class is deprecated?

    So you can't predict the ordering of ACKs and other messages. You can't even predict the ordering of ACKs even if there are np other messagesI have a sequence number put into the datagram packets.
    This is the format of my packets.
    Packet length 16 bytes, consist of :
    - Packet type, 1 byte (This will determine if the packets is a message or an ack).
    - Sequence number, 1 byte.
    - Payload 14 bytes.
    If the receiving socket receive a wrong type of packets (ack instead of message, vica versa), the receiver thread will just drop it.
    And in both cases why start another thread to receive the ACK instead of receiving it in the thread that did the send()? This makes even less sense.By 'receiving it in the thread that did the send()', do you mean that i should put it in the send() method block?
    I pressume that an ack may come before the process finish sending the messages. I put it into a thread so that the process can receive ack while sending another messages.
    It is not important though, because the number of packets that will be sent is relatively small. Should i just change it?
    So, rethink. I would say that your always-listening socket should listen in a single thread for all messages, and notify sending threads about the acknowledgements some other way, e.g. via some data structure. You need that anyway to overcome the lack of ordering among ACKs. You need to associate each sent message that has an ACK outstanding with the thread that sent it, and when it arrives, notify that thread; have the sending thread wait(), almost certainly with a timeout, for that notification, and resend if necessary, adjusting the data structure appropriately so that a late ACK to the previous send is ignored. Or whatever is appropriate to your application protocol.I'll try to redesign my protocol. Thanks for the tips !
    I'm not very good at English. Sorry if i misunderstood you in some way.

  • A thread wouldn't stop

    Hi
    Can anyone explain me this:
    I have a thread running.
    (A class ext. Thread impl. Runnable)
    I wouldn't be able to stop the thread outside with doing:
    mythread = null;
    The thread would stop if I do:
    mythread.stop();
    Although, the compiler says that this method is deprecated.
    How should I stop the thread then?

    Btw, did you say you have a class that both extends Thread and implements Runnable? There is no reason to do that.
    If you extend from Thread, then you start the thread by calling start() on an instance of that object.
    If you implement Runnable, then you create a new Thread object and start this object:
    Runnable target = new MyRunnable();
    Thread thread = new Thread(target);
    thread.start();

  • I have a 8+ Mb VI that won't save when in runnable condition

    I have created a large VI that links to more than 40 sub VIs. I can save any changes I want to the main VI as long as it is not in runnable condition (broken run arrow). However, when I make the final change to put the VI in runnable condition and then try to save, LabVIEW stops responding. This happens whether I choose save, save as, or try to save upon closing the VI.

    I also have a fairly large VI that links to many subVIs but do not run into the problem that you are describing. The following are suggestions that might help.
    One suggestion that I have for you is to reduce the size of your application. I am guessing that you have several bitmaps in your front panel. You can reduce this by loading the image from file using the "Graphics and Sounds" function. This may or may not be included in your development system, depending on what you have.
    One other wild guess is to change the video resolution to 16 bits or lower. I know that LabVIEW will freeze for several minutes when you try and print the front panel. It might not be related but it is worth trying.
    Third option is just to wait for about 5 to 10 minutes to see if LabVIEW
    would come back. I don't believe that it will but try it for giggles.
    Last option is to get on the phone and talk with an Application Engineer about your problem.
    I hope that helps. Regards,
    Shan Pin Koh
    Systems Engineer
    Oakriver Technology

  • Internet explorer warns about my applet, how can I stop it?

    I get the warning "To help protect your security, Internet Explorer has restricted this web page from running scripts or ActiveX controls ..." when running the applet whose code is included below. How can I stop the warning from appearing, it is annoying?
    * @(#)*****.java
    * ******* Applet application
    * @author
    * @version 1.00 2008/2/10
    import java.awt.*;
    import java.applet.*;
    import javax.swing.*;
    public class ****** extends JApplet implements Runnable {
         static int red=0,green=100,blue=0;
         public void init() {
         public void start()
              Thread th = new Thread(this);
              th.start();
         public void run()
              for(int i=1;i<=5;i++)
                   red=i*10;
                   blue=i*8;
                   green=i*15;
                   try{
                        Thread.sleep (200);
                   catch(Exception ex)
                   repaint();
         public void paint(Graphics g) {
              Color hej = new Color(red,green,blue);
              g.drawString("Welcome to Java!!! ", 50, 60 );
    //          setColor(hej.getBlue());
              g.setColor (hej);
              g.fillOval(100,100,500,400);
    }

    You can probably alter your Internet Explorer browser settings by going to the menu <tools><internet options><security> and change one or more of the settings. Be careful about decreasing your security too much. Also, dont expect end-users to lower thier security settings to run your code.

  • How to stop swing timer

    Hello,
    I use Swing timer in my application but it seems that timer.stop() does not work. I put System.out.println("hello") in the method that is the timer's actionlistener and even after I call timer.stop(), it keeps printing "hello". Is there any thing other than timer.stop() that I should do to stop the timer?
    Thanks a lot

    ladybean wrote:
    Thanks a lot for your reply. Well I only have one timer in the code. Another funny thing that is happening is that the timer gets faster over time. As you and I both know, this shouldn't be happening. I believe that you have one Timer variable, but are you sure that you don't have more than one Timer object? Again, this is just a SWAG, but this would also explain the increased speed over time.
    I set the delay time of 1 second but I see that my animation moves faster over time. The reason that I don't upload code is that it's really long and complicated. Maybe I should make it simpler and upload it. This is a very very good idea. We have a construct that's often used here called a SSCCE or "Short, Self Contained, Correct (Compilable), Example" that helps guide folks in creating a small compilable and runnable version of their problem, and often helps them to see their error for themselves (there's a lot to be said for simplifying the problem to examine it). Please have a look at this link for more details: [http://sscce.org/]
    Thanks again though. :)You're welcome. Oh, and if you do resolve this on your own, please post back to let us know what happened and why. Best of luck!

  • How to stop thread permanatly after start?

    hello,
    i am using one thread . that thread start with time delay 10 seconds as follow,
    class tableUpdateThread implements Runnable
        Thread thread;
        int i,j;
        tableUpdateThread()
            thread = new Thread (this, "Table updation");
            thread.start();
        public void run()
            System.out.println (" Update thread starts........");
    try
                      System.out.println (" Update thread starts 4........");
                      Thread.sleep(10000);
                  } catch(InterruptedException ee)
                      System.out.println ("");
    }but, in one point in program, i stopped the thread by,
    tableUpdateThread.thread.stop();but, the thread again started after 10 seconds.
    Whhen I go to another panel, I need to stop the thread permanatly.
    But, in panel 1 I need the thread update the JTable every 10 seconds.
    but in panel 2 I need to stop the thread completely.
    how can I do it.
    please help me.

    Thread.stop has been depracated as unsafe.
    The legitimate way for a thread to stop is for it to return from the run() method.
    Typically you do this by interrupting the thread. If the thread is in sleep or wait this will trigger an InterruptedException. If not, it sets a flag, which the thread should check when it does a loop.
    (If a thread calls sleep or wait after being interrupted, it throws InterruptedException immediately.)

  • Problem Getting Thread to Stop

    Hello,
    I am simulating a race. When the winner has been determined, I need to stop the other threads since the race is over. Here is the code that I have with regards to stopping the threads:
    public void simulateTravelTime() {
    try {
    Thread.sleep((int)(Math.random() * distance * 10));
    //Terminate thread execution if the thread is interrupted.
    catch (InterruptedException e) {
    requestStop();
    public void requestStop() {
    stopThread = true;
    public void run() {
    while (!stopThread && (waterInBucket < fullBucket)) {
    //Code to simulate the race and determine if there is a winner.
    //If there's a winner, stop all threads.
    if (winner == true) {
    int n = group.activeCount();
    Thread[] activeThreads = new Thread[n];
    group.enumerate(activeThreads);
    for(int i=0; i<n; i++)
    activeThreads.requestStop();
    //Interrupt the other threads in case they're sleeping.
    group.interrupt();
    It doesn't like the activeThreads[i].requestStop(); line. Anyone know how to alter my code to fix the problem?
    Thx.

    Ahh, I see. Didn't notice that before.
    Okay, I gotta run, but off the top of my head, I think one of the following should work. I prefer the first:
    * When you create the threads, give each one a name that matches it up to your class. Your clas needs to have a name field to match on, or else a separate map maps the name to the Runnable (your class).
    OR
    * Have your class extend Thread.

Maybe you are looking for