Re-running a Thread

Hi all,
I have a problem with re-running a Thread. I try to reun a Thread via its start()-method. The first time everything works fine. The second time (after the Thread finishes his first execution) the run()-method is never invoked when calling start(). Is this a bug or is there no way to re-use a Thread. Do I have to construct a new Thread instead of re-using the old one?
Thanks for any hint, Mathias

You can only call start() once. When the thread exits its run method, then this thread is stopped and you cannot run it again.
Take a look at the SwingWorker example on how to reuse a thread. It works something like this:
public void run() {
  while (running) {
    // wait until a new task is received
    // run the task
public void newTask(Runnable task) {
  // notify the thread about this new task
public void stopThread() {
  running = false;
  // notify the thread in case it is sleeping
}

Similar Messages

  • How to run a thread for second time ?

    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();

    baskark wrote:
    I have a written a ThreadPool, but I found that basically a thread is not running for the second time. i.e First i call run() method and call stop(). If i call again run() method for the same thread, it is not running. What should I do, If i want to run the thread for the second time ?
    class NewThread implements Runnable {
    String name;
    NewThread(String a) {
    name=a;
    public void run() {
    try{
    for(int i=0;i<5;i++) {
    System.out.println("Thread :" + name + " #" +i);
    Thread.sleep(5);
    catch (Exception e) {
    e.printStackTrace();
    class threadRunnableTest {
    public static void main (String args[]) {
    Runnable runnable=new NewThread("BaSkAr");
    Thread thread = new Thread(runnable);
    try{
    System.out.println("First Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("First Thread it to be stopped!!");
    thread.stop();
    System.out.println("Second Thread is starting !!!");
    thread.start();
    Thread.sleep(2000);
    System.out.println("Second Thread it to be stopped!!");
    thread.stop();
    catch (Exception e) {
    e.printStackTrace();
    It's usually helpful to check the documentation:
    [http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()|http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()]
    start
    public void start()Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
    The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
    It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
    So, make a new java.lang.Thread

  • How do I run a thread without its panel.

    I have created a vi in my application that I run as a thread. I run the thread by using an invoke node.
    When I am testing under LabView everything is fine but when I create the executable I have found problems.
    As I am starting the thread with an invoke node, the vi does not show in the application builder unless I add it as a top level vi. When I add it as a top level vi, the panel is shown when I run the application.
    I don't want to show the panel because firstly theres nothing on it anyway and secondly it looks untidy.
    Dave.

    Brian
    I tried that already with no effect. I have attached an example of my problem. This shows a meter on the front panel. A vi running as a thread writes a value to a global every 20ms and this is then read by the front panel and written to the meter.
    Dave.
    Attachments:
    Thread_test.zip ‏18 KB

  • How do i run two threads with different sleep times?

    How do i run two threads with different sleep times?
    Ive got thread A and thread B, they both update a jpanel.
    They both start when i press the start button.
    However thread A updates every 250ms and thread B updates every 1000ms. i cant just run them both at 250ms becuase this will mess it up.
    So for every four runs of thread A i want thread b to only be run once
    Does anyone know how to do this?
    Thanks, Ant...

    ok, ive done it but now i cant stop it!
    ive added buttons to start and stop, the start button works but the stop button doesnt. why doesnt "t.stop();" work?
        public void run() {
            while(t == Thread.currentThread()) {
                System.out.println("No " + t.getName());
                if (t.getName().equals("1")){
                    try {
                        t.sleep(1000); // in milliseconds
                    } catch (InterruptedException e) {}
                } else{
                    try {
                        t.sleep(250); // in milliseconds
                    } catch (InterruptedException e) {}
        }

  • How to run multiple Thread using Scheduler's in 1.5

    Hi,
    I have a scenario, in which I have to run a Thread at every 15 minutes, If the first Thread is not Finished in 15 min then new Thread has to start.
    Currently I implemeted with java 1.5 schedulers, but the problem is if my first Thread is taking more than 15 min, then no new Thread is starting.
    Following is my Code:
    TestAccountingThread accountingThread = new TestAccountingThread();
    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);
    scheduler.scheduleAtFixedRate( accountingThread, 0, 60, SECONDS );
    Can any one help on this, This is really urgent.
    Regards,
    Suman

    if my first Thread is taking more than 15 min, then no new Thread is startingIf it takes more than 15 min, manually run a new scheduler with initial-delay=0 and shutdown the current one when the current execution is finished --- and repeat this logic in a conditional loop.
    Could this be what you want?

  • Running a Thread in Oracle

    I have a java stored procedure that has a Thread in it. The Thread is bog standard (extends Thread) and all is does is sleep for 20 seconds:
                MyThread myThread = new MyThread();
                first.start(); 
                first.sleep(20000);
                first.finished = true;                    Obviously setting the 'finished' boolean to true breaks out of the run method.
    The problem is that when i run this on my desktop it sleeps for 20 seconds then exits. When I load this class into Oracle it never seems to wake up!
    Am I missing something here? Can you run new Threads in a Java Stored Procedure?
    thanks
    m

    >
    Can you run new Threads
    in a Java Stored Procedure?Probably.
    Sounds like a really bad idea to me though.

  • Running a thread for a specified time

    my main program has 10 threads. i want to run each thread for 30 secs . but if one thread is on progress it may be allowed some time to complete its task otherwise evrbody should return after 30 secs.how can i do it ?
    thankx

    code is hanging...
    also how do i do >>if one thread is on progress it may be allowed some time to complete its task otherwise evrbody should return after 30 secs
    class Shared
    boolean stop=false;
    // do nothing but helps only for synchronisation
    class ThreadProducer1 extends Thread
    {    Shared obj;
         public void run()
         {   long endTime = System.currentTimeMillis() + 30 * 1000;
             long currentTime;
              for (int k=0;k<1000;k++)
              {System.out.println("thread1");     // doing its work
             currentTime=System.currentTimeMillis();
              if (currentTime>endTime) break;
    class ThreadProducer2 extends Thread
    {   Shared obj;
         public void run()
         {   long endTime = System.currentTimeMillis() + 30 * 1000;
             long currentTime;
              for (int k=0;k<1000;k++){
              System.out.println("thread2");     // doing its work
              currentTime=System.currentTimeMillis();
              if (currentTime>endTime) break;}     // doing its work
    class ThreadProducer3 extends Thread
    {   Shared obj;
         public void run()
         {   long endTime = System.currentTimeMillis() + 30 * 1000;
             long currentTime;
              for (int k=0;k<1000;k++)
              System.out.println("thread 3");     // doing its work
              currentTime=System.currentTimeMillis();
              if (currentTime>endTime) break;
              }     // doing its work
    class Test
    public static void main(String argv[])
        try{
         ThreadProducer1 t1 = new ThreadProducer1();
         ThreadProducer2 t2 = new ThreadProducer2();
         ThreadProducer3 t3 = new ThreadProducer3();
         t1.start();
        t2.start();
         t3.start();
        Thread.sleep(30000); // main thread wakes up after 30 secs.
         }catch (InterruptedException ex)
             System.out.println("exception");

  • Help with running multiple threads

    I'm new to programming with threads. I want to know how to run
    multiple threads at the same time. Particularly for making games
    in Java which I'm also begining to learn. For running multiple
    threads at the same time, do you have to put two run() methods
    in the source? If not then how do you make two threads or more
    run at the same time?
    Thanks for helping.

    For running multiple
    threads at the same time, do you have to put two run()
    methods
    in the source? Hi there,
    Each thread is presumably performing a task. You may be performing the same task multiple times or be performing different tasks at once. Either way, each task would typically be contained within the run() method of a class. This class would either be a subclass of java.lang.Thread (extends Thread) or would be an implementation of java.lang.Runnable (implements Runnable). In either case, you would define a method with signature (public void run()...). The difference comes into play when you wish to actually perform one of these tasks. With a subclass of Thread, you would simply perform:
    new MyTask().start();
    With an implementation of Runnable, you would do this:
    new Thread(new MyTask()).start();
    This assumes you don't need to monitor the threads, won't be sending any messages to your tasks or any such thing. If that were the case, you would need to tuck away those returns to new MyTask() for later access.
    In order to launch two threads simultaneously, you would have something along the lines of:
    new MyTask().start();
    new MyOtherTask().start();
    Now it is perfectly possible that MyTask() would complete before MyOtherTask() managed to start in which case it wouldn't appear as if you had actually had multiple threads running, but for non-trivial tasks, the two will likely overlap. And of course, in a game, these tasks would likely be launched in response to user input, which means that you wouldn't have any control over when or in what order they executed.
    Anyhow, it's as simple as that. You should also consider following the Java Threading trail which shows a simple example of using multiple threads. You can find it at:
    http://java.sun.com/docs/books/tutorial/essential/threads/index.html
    Regards,
    Lynn

  • Image to system clipboard running in Thread issue

    In one of my applets I copy an image to the system clipboard. The issue I am having is that if I'm running other threads the "setContents()" method never seems to be allowed to complete or takes a really long time no matter the size of the image. All my threads have "wait" statements and my CPU load is 1%. Has anyone else had this same issue? What is a recommended workaround?

    Do you know that an unsigned applet can't access the clipboard?

  • How to 'STOP' a running java thread in J2ME?

    Dear All,
    How to 'STOP' a running java thread in J2ME?
    In the middleware viewpoint, for some reasons we have to stopped/destroyed the running threads (we have no information how these applications designed).
    But in J2ME, Thread.destroy() is not implemented. Are there other approaches to solve this problem?
    Thanks in advance!
    Jason

    Hi jason,
    Actually there are no methods like stop() and interrupt() to stop the threads in J2ME which is present in normally J2SE Environment.
    But the interrupt method is introduced in Version 1.1 of the CLDC.
    So, we can handle the thread in two ways.
    a) If it is of single thread, then we can use a boolean variable in the run method to hadle it. so when the particular boolean value is changed , it will come out of the thread.
    for eg:
    public class exampleThread implements Runnable
    public boolean exit = false;
    public void run()
    while(!exit)
    #perform task(coding whatever u needed)
    public void exit()
    exit = true;
    b) If it is of many threads then we can handle using the instance of the current thread using currentThread() method
    for eg:
    public class exampleThread implements Runnable
    public Thread latest = null;
    public Thread restart()
    latest = new Thread(this);
    latest.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while( latest == thisThread )
    #perform some tasks(coding part);
    public voi d stopAll()
    latest = null;
    while ( latest == thisThread )
    performOperation1();
    if( latest != thisThread )
    break;
    performOperation2();
    Regards,
    Prathesh Santh.

  • How to run two thread parallel y on two cores of dual-core ??

    I want to run two threads on two cores ???
    is there any package which support parallel computing??
    can we do this by using java.util.concurrency pakage??
    Thanks you
    please Reply.....

    vikram_p wrote:
    I want to run two threads on two cores ???ok
    Threads are automatically spread over the available cores, as the OS sees fit.
    is there any package which support parallel computing??Java does so without any external libraries.
    can we do this by using java.util.concurrency pakage??yes
    One question mark per question is plenty, thank you.

  • How to run the Thread twice

    Why the program only can print from 0 to 9 once, not twice?
    Thank you!
    Here is my program
    class TestThread extends Thread
         String name;
         public void run(){
              for(int i=0;i<10;i++){
              System.out.println(i);
              try{
              sleep((long)(Math.random()*1000));
              }catch(Exception e){
                   System.out.println(e.toString());
         public static void main(String[] args){
              TestThread t = new TestThread();
              TestThread t1 = new TestThread();
              t.start();
              try{
              t.join();
              }catch(Exception e){
              t.start();

    Why the program only can print from 0 to 9 once, not
    twice?
    Thank you!
    Here is my programBecause the run() method returns after printing the numbers once and sleeping a random amount of time. When you return from the run() method, the thread ends.
    Threads cannot be restarted, i.e., if a thread has ended you cannot call start() on it again. If you want to do that, just create a new object and call start() on it.
    Maybe you want a loop in your run() method:
    public void run() {
      while (true) {   // Keep doing this forever!
        for(int i=0;i<10;i++) {
          System.out.println(i);
          try {
            sleep((long)(Math.random()*1000));
          catch(Exception e) {
            System.out.println(e.toString());
    }Jesper

  • Running another thread not to block UI

    I do some heavy operation inside the actionPerformed (load images from File Chooser, resize it for display and populate it in the ScrollPane etc) and I realize that the windows freezes until the whole operation is finished. And it doesn't really help that I do repaint() or validate(). I make some research and some of the books and people from forums say that I actually needed to dispatch another thread to run the heavy operation. So that I won't block the UI interface and can update things accordingly. But the problem is, I don't have any clear example to understand this concept. How to clean up the thread after operation finished. How can a thread notify the progress back and etc. I need to know how much images has been loaded so that I can update the progress bar and so on. Can anyone help me point out a good example? :D

    Think I should show my code snippet to you
    public void actionPerformed(ActionEvent e) {
            if (e.getSource() == BtnBrowse) {
                int returnVal = fcSelectFile.showDialog(this,"Select");
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file= fcSelectFile.getSelectedFiles();
                    //This is where a real application would open the file.
                    Thread worker=new Thread(){
                            public void run(){
                                int count=0;
                                selectedFile=new JLabel[file.length]; 
                                while(count<file.length)
                                {   final int index=count;
                                    String actualFile=file[count].toString();
                                    String fileName= file[count].getName();
                                    selectedFile[count]=new JLabel(createImageIcon(actualFile,fileName));
                                    SwingUtilities.invokeLater(new Runnable(){
                                    public void run(){
                                    PnlImageHolder.add(selectedFile[index]);
                                    PnlImageHolder.repaint();
                                    PnlImageHolder.validate();
                                    count++;
                    worker.start();
                    ScpImageScroller.getViewport().add(PnlImageHolder);
    }

  • How to run two threads simultaneously ....?

    Hello All,
    I Am developing an application which send some data to server and from remote place that data is fetched and displayed.
    For this i am using Java Servlet as a server which accepts data by readObject() method of object output stream and writes using writeObject() method.
    At remote end i am fetching the data and printing that using thread.Data is fetched using URL's method
    URL urlServlet = new URL("URL of servlet");
    URLConnection con = urlServlet.openConnection();But while fetching it takes some time say 1-2sec because of that my display is not continuous.
    I want to write an application such that two threads will be running(in synchronization),second thread will start after few ms of 1st thread.One thread will continuously fetches data and other will display, so that there will be no delay at all while displaying of data.
    How to do this?
    Thanks In Advance.

    Google on: java producer consumer example
    Kaj

  • Run in thread

    say a code like.....
    public static void main(String[] args) {
        for(int i = 0; i < 5; i++)
          new SimpleThread().start();
        System.out.println("All Threads Started");
    each of these threads run() method does calculation and insert DATA to DB ....do we need any synchonisation here ?Actually i fear for data corruption if multiple run method starts entering data into DB .
    can any suggest here better code or safe side[b] if needed at all
    or do i just put SQL query for insertion into DB in my run method ?
    plz comment

    not cleari meant ur that question was not clear.A transaction has a specific meaning in DBs. If multiple threads could possibly affect the same data, then you need to use transactions (and/or Java's syncing) to ensure they don't, or at least get a proper exception when they do.
    run()
    some_class sc=new some_class(Argument);
    String xml=sc.getResult(); // here i have an external
    process
    //parse XML here.
    // send XML data to DB by an SQL query
    }Problem :
    do u think there is any chance of data corruption if
    i create lots of multiple threads ?Again, not enough detail. What data do those threads share, and how do they share it?
    Have you been through the multithreading tutorial? If not, you should:
    http://java.sun.com/docs/books/tutorial/essential/threads/

Maybe you are looking for

  • Time machine won't back up like it used to.

    After months of an almost flawless relationship with my computer & external drives, time machine has found a way to ruin things. I searched the internet wide but still can't find a solution that works for my situation. The problem started when I purc

  • Different Styles in PlainView - Syntax Highlighting?

    Hi, I've managed to extend PlainView and looking at old JEdit code I have the syntax highlighting working for the most part. However, at certain times while typing the cursor starts to get way ahead of the text it's typing. And as I backspace on the

  • [svn:cairngorm3:] 16817: Migration to Flex 4.1 SDK.

    Revision: 16817 Revision: 16817 Author:   [email protected] Date:     2010-07-05 14:05:28 -0700 (Mon, 05 Jul 2010) Log Message: Migration to Flex 4.1 SDK. Modified Paths:     cairngorm3/trunk/libraries/ContractTest/.actionScriptProperties Added Paths

  • How to add icon field in the alv grid output

    Hi Experts, i need to add one icom column in the alvgrid.That icon if the contract is inacitve then it should shows inactive symbol.if the contract is account assignment lock then it should show that lock symbol.Please send me the any code or approac

  • Need help installing Canon MG6220 using 10.8.2

    Need step by step walk throught on how to install drivers and software. Thank You for Your Time and Effort!!!