Results 1 to 7 of 7
  1. #1
    ggyyree is offline Member
    Join Date
    Nov 2010
    Posts
    15
    Rep Power
    0

    Question Why are the threads start and terminate randomly?

    Hi there,

    I got the program below. I am wondering why are the threads start and terminate randomly? Everytime, I run the program, it produces different results.

    I know that these four threads have got same normal priority (should be 5), and under windows there is something called timeslice. Then these four threads rotate using this timeslice. How do we know what exactly the timeslice is in seconds? If the timeslice is fix, then why the results are ramdom?

    Thanks in advance! :D

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package mythreadone;
    
    /**
     *
     * @author Administrator
     */
    public class MyThreadOne implements Runnable {
    
        String tName;
        Thread t;
    
        MyThreadOne(String threadName) {
            tName = threadName;
            t = new Thread(this, tName);
            t.start();
        }
    
        public void run() {
            try {
                System.out.println("Thread: " + tName);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("Exception: Thread "
                        + tName + " interrupted");
            }
            System.out.println("Terminating thread: " + tName);
        }
    
        public static void main(String args[]) {
            
            // Why are the threads start and terminate randomly?
            new MyThreadOne("1");
            new MyThreadOne("2");
            new MyThreadOne("3");
            new MyThreadOne("4");
            try {
                Thread.sleep(10000);
                // Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println(
                        "Exception: Thread main interrupted.");
            }
            System.out.println(
                    "Terminating thread: main thread.");
        }
    }

  2. #2
    ggyyree is offline Member
    Join Date
    Nov 2010
    Posts
    15
    Rep Power
    0

    Default

    BTW, I also test with the change

    Java Code:
    Thread.sleep(2000);
    Then I try the program, it seems the main thread always terminates before all the child threads end.

    The main thread also ends randomly, but it always ends before all the child threads finish.

    Is there a theory behind? Cheers,


    Aaron

  3. #3
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    try having the main thread wait for the child threads, such as using the thread.join() method. This also requires we keep a reference to the threads.

    Changes in red,

    Java Code:
    /**
     * returns the thread object used inside this MyThread runnable.
     */
    [COLOR="Sienna"]public Thread getThread() {
      return this.t;
    }
    [/COLOR]
    
    public static void main(String args[]) {
            
            // Why are the threads start and terminate randomly?
           [COLOR="Sienna"]Thread t1 = [/COLOR] new MyThreadOne("1");
            [COLOR="Sienna"]Thread t1 =[/COLOR] new MyThreadOne("2");
            [COLOR="Sienna"]Thread t3 = [/COLOR]new MyThreadOne("3");
            [COLOR="Sienna"]Thread t4 =[/COLOR] new MyThreadOne("4");
            try {
    [COLOR="Sienna"]            //NO -> Thread.sleep(10000);
                // now wait for each thread to exit.
                t1.getThread().join();
                t2.getThread()..join();
                t3.getThread()..join();
                t4.getThread()..join();
                // we could also do t1.isAlive();[/COLOR]
            } catch (InterruptedException e) {
                System.out.println(
                        "Exception: Thread main interrupted.");
            }
            System.out.println(
                    "Terminating thread: main thread.");
        }

  4. #4
    ggyyree is offline Member
    Join Date
    Nov 2010
    Posts
    15
    Rep Power
    0

    Default

    Hey, thanks a lot for your reply. I read something about join() and isAlive() too, but it doesn't solve my problem.

    1. In my first post, I set in the main function:

    Java Code:
    Thread.sleep(10000);
    and I run the program it gives:

    Java Code:
    Thread: 1
    Thread: 4
    Thread: 2
    Thread: 3
    Terminating thread: 1
    Terminating thread: 3
    Terminating thread: 4
    Terminating thread: 2
    Terminating thread: main thread.
    BUILD SUCCESSFUL (total time: 10 seconds)
    Run it again, it gives:

    Java Code:
    Thread: 2
    Thread: 4
    Thread: 3
    Thread: 1
    Terminating thread: 2
    Terminating thread: 1
    Terminating thread: 3
    Terminating thread: 4
    Terminating thread: main thread.
    BUILD SUCCESSFUL (total time: 10 seconds)
    And my question was why it outputs like this? It suppose to be:

    Java Code:
    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Terminating thread: 1
    Terminating thread: 2
    Terminating thread: 3
    Terminating thread: 4
    Terminating thread: main thread.
    BUILD SUCCESSFUL (total time: 10 seconds)
    Why these four threads start and finish randomly each time I run the program? I use Windows, suppose there is a timeslice (i.e. 1 second), these threads have the same priority. Then the threads should start and finish in turn one by one. Am I right?
    Last edited by ggyyree; 12-14-2010 at 01:04 PM.

  5. #5
    ggyyree is offline Member
    Join Date
    Nov 2010
    Posts
    15
    Rep Power
    0

    Default

    2. My second question is:

    When I change the codes in the 'main' function into:

    Java Code:
    Thread.sleep(10000); -> Thread.sleep(2000);
    it gives me the results like:

    Java Code:
    Thread: 1
    Thread: 4
    Thread: 3
    Thread: 2
    Terminating thread: main thread.
    Terminating thread: 1
    Terminating thread: 4
    Terminating thread: 3
    Terminating thread: 2
    BUILD SUCCESSFUL (total time: 2 seconds)
    Run it again:

    Java Code:
    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Terminating thread: 3
    Terminating thread: main thread.
    Terminating thread: 4
    Terminating thread: 2
    Terminating thread: 1
    BUILD SUCCESSFUL (total time: 2 seconds)
    I tried several times. The main thread always terminates before or after the first child thread finished.

    My question is why it doesn't output something like:

    Java Code:
    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Terminating thread: 3
    Terminating thread: 4
    Terminating thread: 2
    Terminating thread: main thread.
    Terminating thread: 1
    BUILD SUCCESSFUL (total time: 2 seconds)
    or

    Java Code:
    Thread: 1
    Thread: 2
    Thread: 3
    Thread: 4
    Terminating thread: 3
    Terminating thread: 4
    Terminating thread: 2
    Terminating thread: 1
    Terminating thread: main thread.
    BUILD SUCCESSFUL (total time: 2 seconds)

  6. #6
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    Sometimes the when the system gets around to starting and running a thread, depending on anything of what else is running on the system at that time, the phase of the moon, any number of variables, executing the same thread might receive more or less time slices, even though you specify the priority and this causes the out of ordering of thread start / finish times.

    If you really wanted to have it so threads 1,2,3,4 will start in that order, and finish in that order, I'm not entirely sure there is a way to guarantee that will alwyas happen. We can do something like
    Java Code:
    // in the main thread;
    t1.start();
    Thread.sleep(50);
    t2.start();
    Thread.sleep(50);
    t3.start();
    Thread.sleep(50);
    t4.start();
    Thread.sleep(50);
    where we are intentionally giving a tiny bit of lead time for the thread to start up.

    another idea, perhaps it is the operating system or java vm operation of 'creating a thread' that randomly takes a variable amount of time to complete. we can try some kind of two step approach, where we start the thread. and the thread immediately goes into a wait state, then the main body executes a notify when its ready to have all of the threads ran.

    for example,

    Java Code:
    public class MyThreadOne implements Runnable {
    
        String tName;
        Thread t;
    
        MyThreadOne(String threadName) {
            tName = threadName;
            t = new Thread(this, tName);
            t.start();
        }
    
        public void run() {
    [COLOR="Red"]      // wait for me to be notified by main thread before continuing.
          synchronized (t) {
            wait(); 
          }
          // after main thread notifies we run normally.[/COLOR]
            try {
                System.out.println("Thread: " + tName);
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("Exception: Thread "
                        + tName + " interrupted");
            }
            System.out.println("Terminating thread: " + tName);
        }
    
      /**
     * returns the thread object used inside this MyThread runnable.
     */
    public Thread getThread() {
      return this.t;
    }
    
    
    public static void main(String args[]) {
           // initialize threads. they won't run yet because of that wait() we added.        
           Thread t1 =  new MyThreadOne("1");
            Thread t1 = new MyThreadOne("2");
            Thread t3 = new MyThreadOne("3");
            Thread t4 = new MyThreadOne("4");
    
           [COLOR="Red"]// issue a notify to each thread to have them start up
           synchronized(t1.getThread()) {
             t1.getThread().notify();
           }
           // optional: Thread.sleep(50)  here if we want to try to give some lead time...
    
           synchronized(t2.getThread()) {
             t2.getThread().notify();
           }
    
           synchronized(t3.getThread()) {
             t3.getThread().notify();
           }
    
           synchronized(t4.getThread()) {
             t4.getThread().notify();
           }[/COLOR]
    
            try {
                // now wait for each thread to exit.
                t1.getThread().join();
                t2.getThread().join();
                t3.getThread().join();
                t4.getThread().join();
                // we could also do t1.isAlive();
            } catch (InterruptedException e) {
                System.out.println(
                        "Exception: Thread main interrupted.");
            }
            System.out.println(
                    "Terminating thread: main thread.");
        }
    }
    where we can do a wait(), notify() on any object really. I just chose to use the thread object inside the runnable here because it's something the thread and main() can share. and alternatively, if the method was declared as synchronized (e.g. public synchronized void run() ) we wouldn't need to wrap these inside the synchronized() { } block. but the main() method is not synchronized so we'd still need those there I think.
    Last edited by travishein; 12-14-2010 at 04:23 PM.

  7. #7
    ggyyree is offline Member
    Join Date
    Nov 2010
    Posts
    15
    Rep Power
    0

    Default

    Thanks very much travishein!

    Yes, I get much clearer now. Also your solution provides lots of details that I need look into. Cheers!:D

Similar Threads

  1. how can terminate the string
    By abhay23k in forum Threads and Synchronization
    Replies: 4
    Last Post: 08-10-2010, 09:25 PM
  2. Threads don't start after few iterations
    By gaurav2211 in forum Threads and Synchronization
    Replies: 2
    Last Post: 12-18-2009, 10:34 AM
  3. event that terminate function
    By itaipee in forum AWT / Swing
    Replies: 6
    Last Post: 12-08-2009, 04:15 PM
  4. crawler doesn't start threads.
    By Pierced1 in forum Threads and Synchronization
    Replies: 2
    Last Post: 09-28-2009, 09:02 PM
  5. 3 errors and then terminate program
    By hezfast2 in forum New To Java
    Replies: 2
    Last Post: 05-20-2008, 02:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •