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

    Question Question about 'main thread' and the thread it creates

    Hi guys,

    I've read a tutorial about the Java threads. Here is an example given below.

    My question is when the main thread creates a new thread t, and what is the status of the main thread during thread t is active?

    My understanding is:

    Main thread (active) -> create t (active) -> main thread (sleep) -> Interrupt t -> main (active).

    So when t is active, main thread is sleep. Because it uses t.join(1000), and main thread will only sleep for only one second. Is that correct?

    Except this one second sleep, will both the main thread and t thread be active?

    Thanks a lot!!!!


    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 * 60 * 60;
    
            //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
    Join Date
    Dec 2010
    Posts
    22
    Rep Power
    0

    Default

    Threading in Java is truly 'asynchronous' i.e. there is never a case when two thread will be working at the same time. There is no multi-tasking. But, in Java, based on the priority, there is an arbitrary logic where JVM will place one thread on hold and start executing the other thread. Actually, the logic is not arbitary - JVM follows a routine, but if two thread are in similar state, which one will be picked is not controlled and cant be controlled.

    However, in your case, .join() will mean that the threads will execute concurrently. let me know if this makes sense, or I can provide a sample.

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

    Default

    Hi Kapil,

    Thanks very much for your reply. I am still a little bit confusing.

    1. You said Java threading is purely 'Asynchronous', which means there is not possible for two or more thread working or running at the same time. Then actually what is the Java multi-threading doing? If all the threads are waiting in a queue, then how does the multi-threading save time and be more efficiency?

    2. If multi-threads can't run at the same time. Then why did you say that when we use .join(), there are threads executing concurrently?

    3. Also if the thread are in a queue, how do they order? You said arbitrary, right?

    Cheers,
    Aaron

    Quote Originally Posted by Kapil Viren Ahuja View Post
    Threading in Java is truly 'asynchronous' i.e. there is never a case when two thread will be working at the same time. There is no multi-tasking. But, in Java, based on the priority, there is an arbitrary logic where JVM will place one thread on hold and start executing the other thread. Actually, the logic is not arbitary - JVM follows a routine, but if two thread are in similar state, which one will be picked is not controlled and cant be controlled.

    However, in your case, .join() will mean that the threads will execute concurrently. let me know if this makes sense, or I can provide a sample.

  4. #4
    Join Date
    Dec 2010
    Posts
    22
    Rep Power
    0

    Default

    Quote Originally Posted by ggyyree View Post
    1. You said Java threading is purely 'Asynchronous', which means there is not possible for two or more thread working or running at the same time. Then actually what is the Java multi-threading doing? If all the threads are waiting in a queue, then how does the multi-threading save time and be more efficiency?
    This of how you work on two programs. If you have to create a document and an excel spreadsheet there are two ways of doing it. 1. Open up Word and finish all of it. Then open Excel and finish all of it. Basically one after the another. In simple world this is how it works. But, the multi-threading world you will be able to do some work in Word if there is any background work to be done then you do some work in Excel. Now lets look how Java does it. If you have two tasks and one task needs some data from a DB. Then that task has to wait for DB to run the query and return data. In #1 approach the task will keep on waiting. But in multi threading, the processor is allocated to the second task and they do work whilt task# has to wait. However, the processor CPU application goes is based on miliseconds and maybe nano seconds and thats how multi threading works in JVM. However, recently microsoft in their dotNet version have started to implement multu-threading at a core level and there have been areas where some work has been done in Java too.


    Quote Originally Posted by ggyyree View Post
    2. If multi-threads can't run at the same time. Then why did you say that when we use .join(), there are threads executing concurrently?
    If you want one thread to execute after another, then you use join. But if this is needed, you should think if you have a need for multi-threading


    Quote Originally Posted by ggyyree View Post
    3. Also if the thread are in a queue, how do they order? You said arbitrary, right?
    Not everything is arbitary. There is a logic behind how JVM decided threads. And this is a lengthy one. I think I will be able to find a link that explains this well - just that I dont have my personal laptop on me right now. I will check it up in the night and sahre with you.


    Hope this was helpful. Please feel free to ask any questions that you may have. I know what you are going through because I went through the same process when I was getting started on multi threading.:)

  5. #5
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Kapil Viren Ahuja View Post
    Threading in Java is truly 'asynchronous' i.e. there is never a case when two thread will be working at the same time.
    Rubbish; on a multi core processor multiple threads (can) run at the same time.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    Join Date
    Dec 2010
    Posts
    22
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Rubbish; on a multi core processor multiple threads (can) run at the same time.
    Try it - you will be surprised. Also, i did mention that MS and others are doing work in this area. What are are saying is multi-processor programming. That is a different thing.
    Last edited by Kapil Viren Ahuja; 12-09-2010 at 08:19 PM. Reason: adding more explanation

  7. #7
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Kapil Viren Ahuja View Post
    Try it - you will be surprised. Also, i did mention that MS and others are doing work in this area. What are are saying is multi-processor programming. That is a different thing.
    Even microsoft can do it; given multiple cores, multiple threads can run on that shame of an OS.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  8. #8
    Join Date
    Dec 2010
    Posts
    22
    Rep Power
    0

    Default

    Quote Originally Posted by JosAH View Post
    Even microsoft can do it; given multiple cores, multiple threads can run on that shame of an OS.

    kind regards,

    Jos
    Try it for a single JVM. As for MS, i am not talking about Word and Excel or windows. I am talking about dotNet programming. They have created a new multi-processor environment in their 3.5 or 4.5 version where they handle Cores and I/O methods. Before that there was no way to control what thread goes where.

    Same if the case in JVM too - You can not control what happens how with threads running on a multi-core machine.

  9. #9
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,519
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Kapil Viren Ahuja View Post
    Same if the case in JVM too - You can not control what happens how with threads running on a multi-core machine.
    That's true: the JVM doesn't schedule on which core a thread should run, that's the job of the OS. If the 'affinity' of the JVM is set to all cores, threads will be spread over those cores.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  10. #10
    Join Date
    Dec 2010
    Posts
    22
    Rep Power
    0

    Default

    I guess we finally are singing off the same sheet of music.

    And i want to add - On a shared server (like in production) you will have multiple JVMs running to most utilize the JVM and multi-core features may not get exploit. The idea is - we will not be able to control what goes where. And we end up still being on a single core.

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

    Thumbs up

    Hi Kapil,

    Thanks a lot for your reply! Still got some questions:

    1. You gave two examples. One is Word and Excel, and one has two tasks. Actually there are the same situation.

    If there is no multi-threading, it is simple, task two always follows task one, and task two only starts after task one finishes. Perfect.

    If there is multi-threading, ok, when task one has something to wait (read DB or do something at the background or whatever), task two starts to work. Problem:

    Assume task one use one thread, and task two use another one. What does the one at background use? If the one at background possesses another thread (e.g. reading DB or saving files in Word), then actually there are two threads running at the same time!!! (i.e. task two thread and background task thread).

    I think the possible explanation is the task one and task two threads are in the same process; however, the background thread is in another separate process. Am I right?

    2. Another thing is when task one thread is sleep. Suppose task two thread starts and works happily, after a certain time task one thread is wake up (e.g. reading DB finishes), then task two should stop now or task one must wait?

    3. You said '.join() will mean that the threads will execute concurrently' and also then said 'If you want one thread to execute after another, then you use join.', which seems conflict. For my understanding if join makes threads concurrent then how does it makes one thread execute after another then?

    4. I really appreciate if you could find the link about the multi-threading order, and post it here.


    Thank you very much and have a nice weekend!



    wbr,
    Aaron

  12. #12
    Join Date
    Dec 2010
    Posts
    22
    Rep Power
    0

    Default

    Quote Originally Posted by ggyyree View Post
    Assume task one use one thread, and task two use another one. What does the one at background use? If the one at background possesses another thread (e.g. reading DB or saving files in Word), then actually there are two threads running at the same time!!! (i.e. task two thread and background task thread).

    I think the possible explanation is the task one and task two threads are in the same process; however, the background thread is in another separate process. Am I right?
    - Yes you are right. If As long as the threads are owned by the process started by JVM), the deci


    Quote Originally Posted by ggyyree View Post
    2. Another thing is when task one thread is sleep. Suppose task two thread starts and works happily, after a certain time task one thread is wake up (e.g. reading DB finishes), then task two should stop now or task one must wait?
    - Right; and that is something that JVM decided. This is the reason, we should use synchronized blocks on resources because in case multiple threads are to share resources it will cause issues.


    Quote Originally Posted by ggyyree View Post
    3. You said '.join() will mean that the threads will execute concurrently' and also then said 'If you want one thread to execute after another, then you use join.', which seems conflict. For my understanding if join makes threads concurrent then how does it makes one thread execute after another then?
    - sorry for confusion. I meant - sequentially not concurrently

    Quote Originally Posted by ggyyree View Post
    4. I really appreciate if you could find the link about the multi-threading order, and post it here.
    - Thread Synchronization and the Java Monitor


    Thank you very much and have a nice weekend!



    wbr,
    Aaron[/QUOTE]

Similar Threads

  1. Replies: 5
    Last Post: 06-22-2010, 03:51 PM
  2. Trigger main thread method from secondary thread?
    By DigitalMan in forum Threads and Synchronization
    Replies: 8
    Last Post: 01-26-2010, 02:13 AM
  3. Replies: 1
    Last Post: 07-16-2009, 10:35 AM
  4. data from the main/GUI thread to another runnin thread...
    By cornercuttin in forum Threads and Synchronization
    Replies: 2
    Last Post: 04-23-2008, 10:30 PM
  5. main thread question?
    By frejon26 in forum New To Java
    Replies: 1
    Last Post: 01-24-2008, 10:13 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
  •