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 8527043
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T08:26:40+00:00 2026-06-11T08:26:40+00:00

Possible Duplicate: Trying to loop 3 threads in a specific order everytime I want

  • 0

Possible Duplicate:
Trying to loop 3 threads in a specific order everytime

I want to access two different methods of the same object from two threads one after another. Here is my code,

public class ThreadCoordination
{
private Thread threadSayHello;
private Thread threadSayWorld;
private boolean threadSayWorldStarted = false;

public ThreadCoordination()
{
    createThreads();
}

private void createThreads()
{
    threadSayWorld = new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                // while (true)
                {
                    sayWorld();
                }
            }
            catch (InterruptedException ex)
            {}
        }
    });

    threadSayHello = new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                // while (true)
                {
                    sayHello();

                    if (!threadSayWorldStarted)
                    {
                        threadSayWorldStarted = true;
                        threadSayWorld.start();
                    }
                }
            }
            catch (InterruptedException ex)
            {}
        }
    });

    threadSayHello.start();
}

private synchronized void sayHello() throws InterruptedException
{
    System.out.print("Hello ");
}

private synchronized void sayWorld() throws InterruptedException
{
    System.out.println("World!");
}

public static void main(String[] args)
{
    new ThreadCoordination();
}
}

If i uncomment the call while(true), then I’ll expecting the output like this,

Hello World!
Hello World!
Hello World!
Hello World!
...

Please guide me how do I do it.
Raja.

I don’t know whether I can edit the closed post. I just want to post the solution as far as I know.

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class SequenceAccess
{
private ReentrantLock myLock;
private Condition ensureSequence;
private int sequenceNo = 1;

public SequenceAccess()
{
    myLock = new ReentrantLock();
    ensureSequence = myLock.newCondition();

    startThreads();
}

private void startThreads()
{
    new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                while (true)
                    method1();
            }
            catch (InterruptedException ex)
            {}
        }
    }).start();

    new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                while (true)
                    method2();
            }
            catch (InterruptedException ex)
            {}
        }
    }).start();

    new Thread(new Runnable()
    {
        public void run()
        {
            try
            {
                while (true)
                    method3();
            }
            catch (InterruptedException ex)
            {}
        }
    }).start();
}

private void method1() throws InterruptedException
{
    myLock.lock();
    try
    {
        while (sequenceNo != 1)
            ensureSequence.await();

        sequenceNo = 2;
        System.out.println("Method 1");
        ensureSequence.signalAll();
    }
    finally
    {
        myLock.unlock();
    }
}

private void method2() throws InterruptedException
{
    myLock.lock();
    try
    {
        while (sequenceNo != 2)
            ensureSequence.await();

        sequenceNo = 3;
        System.out.println("Method 2");
        ensureSequence.signalAll();
    }
    finally
    {
        myLock.unlock();
    }
}

private void method3() throws InterruptedException
{
    myLock.lock();
    try
    {
        while (sequenceNo != 3)
            ensureSequence.await();

        sequenceNo = 1;
        System.out.println("Method 3");
        ensureSequence.signalAll();
    }
    finally
    {
        myLock.unlock();
    }
}

public static void main(String[] args)
{
    new SequenceAccess();
}
}
  • 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-06-11T08:26:42+00:00Added an answer on June 11, 2026 at 8:26 am

    The JVM does not guarantee order of thread execution

    In fact the JVM spec could be met entirely by running the hello thread until it terminates and then running the world thread until it terminates (with your program as written)

    You will need to introduce some sort of token to be shared between the two threads and then have that token shuttled back and forth.

    The token could be as simple as a Boolean which is true if hello has been output and false if world has been output.

    Each thread will then have to spin (or wait for a condition – better performance with a condition) until the Boolean matches its expected state.

    I recommend getting your hands on the most excellent “java concurrency in practice” book

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

Sidebar

Related Questions

Possible Duplicate: Comparing Two Arrays Using Perl I am trying to find elements that
Possible Duplicate: MVC3 custom validation: compare two dates I am trying to make a
Possible Duplicate: before_filter :require_owner I am trying to restrict access to certain actions using
Possible Duplicate: Loop through Json object { data: [ { name: Jen, id: 1
Possible Duplicate: setTimeout in a for-loop and pass i as value i am trying
Possible Duplicate: Multiple index variables in PHP foreach loop I am trying to create
Possible Duplicate: php in background exec() function I am trying to run two exec
Possible Duplicate: Simple and clean xml manipulation in PHP I trying to reference specific
Possible Duplicate: writing many files in a for loop using R I am trying
Possible Duplicate: Enumerating threads in Windows I am trying to enumerate all threads belonging

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.