Results 1 to 6 of 6
  1. #1
    mochajava is offline Member
    Join Date
    Feb 2011
    Posts
    7
    Rep Power
    0

    Default basic threads question

    Hello,

    i have just started with java and am trying to understand the behavior of thread.

    i am looking at the simple thread example on the oracle site (Ref: The SimpleThreads Example (The Java™ Tutorials > Essential Classes > Concurrency))


    from the reference code, in the following snippet of code where t is obviously a thread

    Java Code:
      t.interrupt();        
      t.join();
    if t has been interrupted by invoking t.interrupt in the main code, then how can the main thread join it with the t.join code later.

    in fact when i commented out t.join, it does not appear to have any change in the behavior of the program. the entire code of the program is below



    Java Code:
    public class SimpleThreads {
    
        //Display a message, preceded by the name of the current thread
        static void threadMessage(String message) {
            String threadName = Thread.currentThread().getName();
            System.out.format("%s: %s%n", threadName, message);
        }
    
        private static class MessageLoop implements Runnable {
            public void run() {
                String importantInfo[] = {
                    "Mares eat oats",
                    "Does eat oats",
                    "Little lambs eat ivy",
                    "A kid will eat ivy too"
                };
                try {
                    for (int i = 0; i < importantInfo.length; i++) {
                        //Pause for 4 seconds
                        Thread.sleep(4000);
                        //Print a message
                        threadMessage(importantInfo[i]);
                    }
                } catch (InterruptedException e) {
                    threadMessage("I wasn't done!");
                }
            }
        }
    
        public static void main(String args[]) throws InterruptedException {
    
    
            //Delay, in milliseconds before we interrupt MessageLoop
            //thread (default one hour).
            long patience = 1000 * 8;
    
            //If command line argument present, gives patience in seconds.
            if (args.length > 0) {
                try {
                    patience = Long.parseLong(args[0]) * 1000;
                } catch (NumberFormatException e) {
                    System.err.println("Argument must be an integer.");
                    System.exit(1);
                }
    
            }
    
            threadMessage("Starting MessageLoop thread");
            long startTime = System.currentTimeMillis();
            Thread t = new Thread(new MessageLoop());
            t.start();
    
            threadMessage("Waiting for MessageLoop thread to finish");
            //loop until MessageLoop thread exits
            while (t.isAlive()) {
                threadMessage("Still waiting...");
                //Wait maximum of 1 second for MessageLoop thread to
                //finish.
                t.join(1000);
                if (((System.currentTimeMillis() - startTime) > patience) &&
                        t.isAlive()) {
                    threadMessage("Tired of waiting!");
                    t.interrupt();
                    //Shouldn't be long now -- wait indefinitely
                    //t.join();
                }
    
            }
            threadMessage("Finally!");
        }
    }

  2. #2
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    'join' blocks until the run method exits. If the 'run' method has already exited, then join has no effect. In your specific example, interrupt will cause the 'run' method to exit, but that is not generally true. 'interrupt' does not force threads to exit, instead, it causes wait's and sleep's to throw InterruptedExceptions.

  3. #3
    mochajava is offline Member
    Join Date
    Feb 2011
    Posts
    7
    Rep Power
    0

    Default

    Many thanks for the reply,

    so in my specific example, the t.join does not serve any purpose as the t.interrupt is causing run to exit.

    and in a general case, the interrupt can cause wait and sleep to throw the INterruptedExceptions, correct?

    what are the conditions under which wait will throw an interrupted exception? the following page
    http://download.oracle.com/javase/tu...guardmeth.html states:

    "Like many methods that suspend execution, wait can throw InterruptedException."
    Last edited by mochajava; 02-12-2011 at 02:46 PM. Reason: updated info and understanding

  4. #4
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    wait() will throw an InterruptedException when you call the 'interrupt' method on the thread. It can also happen spontaneously (for no apparent reason) due to the way condition variables work under the hood.

  5. #5
    mochajava is offline Member
    Join Date
    Feb 2011
    Posts
    7
    Rep Power
    0

    Default

    thank for the explanation. any articles you recommend which will give me some understanding of what happens "under the hood". the oracle tutorials are a bit sketchy on detail.

  6. #6
    toadaly is offline Senior Member
    Join Date
    Jan 2009
    Posts
    671
    Rep Power
    6

    Default

    Well, the interrupts that can happen 'under the hood' are at the OS level, so I wouldn't expect to find much on it at Oracle. Java is built on the underlying thread library, and if you want to learn everything you ever wanted to know about condition variables (well, maybe not everything, but a good intro to why interrupts can happen spontaneously)...

    pthread_cond_wait(3): wait on condition - Linux man page

Similar Threads

  1. Basic JSP question..
    By casid in forum JavaServer Pages (JSP) and JSTL
    Replies: 4
    Last Post: 12-28-2009, 07:51 PM
  2. threads question
    By sandor in forum Threads and Synchronization
    Replies: 9
    Last Post: 02-07-2009, 09:57 PM
  3. Basic question on OOP.
    By madthinker in forum New To Java
    Replies: 7
    Last Post: 01-26-2009, 08:09 PM
  4. Basic question about EJB
    By javaplus in forum Enterprise JavaBeans (EJB)
    Replies: 2
    Last Post: 07-15-2008, 06:44 PM
  5. Very basic question
    By gvi in forum New To Java
    Replies: 2
    Last Post: 10-30-2007, 07:30 PM

Posting Permissions

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