Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7088031
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T07:44:51+00:00 2026-05-28T07:44:51+00:00

I’m trying to understand how threads work, and I wrote a simple example where

  • 0

I’m trying to understand how threads work, and I wrote a simple example where I want to create and start a new thread, the thread, display the numbers from 1 to 1000 in the main thread, resume the secondary thread, and display the numbers from 1 to 1000 in the secondary thread. When I leave out the Thread.wait()/Thread.notify() it behaves as expected, both threads display a few numbers at a time. When I add those functions in, for some reason the main thread’s numbers are printed second instead of first. What am I doing wrong?

public class Main {

    public class ExampleThread extends Thread {

        public ExampleThread() {
            System.out.println("ExampleThread's name is: " + this.getName());
        }

        @Override
        public void run() {         
            for(int i = 1; i < 1000; i++) {
                System.out.println(Thread.currentThread().getName());
                System.out.println(i);
            }
        }
    }

    public static void main(String[] args) {
        new Main().go();
    }

    public void go() {
        Thread t = new ExampleThread();
        t.start();

        synchronized(t) {
            try {
                t.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        for(int i = 1; i < 1000; i++) {
            System.out.println(Thread.currentThread().getName());
            System.out.println(i);
        }

        synchronized(t) {
            t.notify();
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T07:44:52+00:00Added an answer on May 28, 2026 at 7:44 am

    You misunderstand how wait/notify works. wait does not block the thread on which it is called; it blocks the current thread until notify is called on the same object (so if you have threads A and B and, while in thread A, called B.wait(), this will stop thread A and not thread B – for as long as B.notify() is not called).

    So, in your specific example, if you want main thread to execute first, you need to put wait() inside the secondary thread. Like this:

    public class Main {
    
        public class ExampleThread extends Thread {
    
            public ExampleThread() {
                System.out.println("ExampleThread's name is: " + this.getName());
            }
    
            @Override
            public void run() {         
                synchronized (this) {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                    }
                }
                for(int i = 1; i < 1000; i++) {
                    System.out.println(Thread.currentThread().getName());
                    System.out.println(i);
                }
            }
        }
    
        public static void main(String[] args) {
            new Main().go();
        }
    
        public void go() {
            Thread t = new ExampleThread();
            t.start();
    
            for(int i = 1; i < 1000; i++) {
                System.out.println(Thread.currentThread().getName());
                System.out.println(i);
            }
    
            synchronized(t) {
                t.notify();
            }
        }
    }
    

    However, even this code may not work like you want. In a scenario where the main thread gets to the notify() part before the secondary thread had a chance to get to the wait() part (unlikely in your case, but still possible – you can observe it if you put Thread.sleep at the beginning of the secondary thread), the secondary thread will never be waken up. Therefore, the safest method would be something similar to this:

    public class Main {
    
        public class ExampleThread extends Thread {
    
            public ExampleThread() {
                System.out.println("ExampleThread's name is: " + this.getName());
            }
    
            @Override
            public void run() {
                synchronized (this) {
                    try {
                        notify();
                        wait();
                    } catch (InterruptedException e) {
                    }
                }
                for(int i = 1; i < 1000; i++) {
                    System.out.println(Thread.currentThread().getName());
                    System.out.println(i);
                }
            }
        }
    
        public static void main(String[] args) {
            new Main().go();
        }
    
        public void go() {
            Thread t = new ExampleThread();
            synchronized (t) {
                t.start();
                try {
                    t.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            for(int i = 1; i < 1000; i++) {
                System.out.println(Thread.currentThread().getName());
                System.out.println(i);
            }
    
            synchronized(t) {
                t.notify();
            }
        }
    }
    

    In this example the output is completely deterministic. Here’s what happens:

    1. Main thread creates a new t object.
    2. Main thread gets a lock on the t monitor.
    3. Main thread starts the t thread.
    4. (these can happen in any order)
      1. Secondary thread starts, but since main thread still owns the t monitor, the secondary thread cannot proceed and must wait (because its first statement is synchronized (this), not because it happens to be the t object – all the locks, notifies and waits could as well be done on an object completely unrelated to any of the 2 threads with the same result.
      2. Primary thread continues, gets to the t.wait() part and suspends its execution, releasing the t monitor that it synchronized on.
    5. Secondary thread gains ownership of t monitor.
    6. Secondary thread calls t.notify(), waking the main thread. The main thread cannot continue just yet though, since the secondary thread still holds ownership of the t monitor.
    7. Secondary thread calls t.wait(), suspends its execution and releases the t monitor.
    8. Primary thread can finally continue, since the t monitor is now available.
    9. Primary thread gains ownership of the t monitor but releases it right away.
    10. Primary thread does its number counting thing.
    11. Primary thread again gains ownership of the t monitor.
    12. Primary thread calls t.notify(), waking the secondary thread. The secondary thread cannot continue just yet, because the primary thread still holds the t monitor.
    13. Primary thread releases the t monitor and terminates.
    14. Secondary thread gains ownership of the t monitor, but releases it right away.
    15. Secondary thread does its number counting thing and then terminates.
    16. The entire application terminates.

    As you can see, even in such a deceptively simple scenario there is a lot going on.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I want use html5's new tag to play a wav file (currently only supported
i want to parse a xhtml file and display in UITableView. what is the
I'm trying to create an if statement in PHP that prevents a single post
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
Specifically, suppose I start with the string string =hello \'i am \' me And

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.