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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T13:10:23+00:00 2026-06-12T13:10:23+00:00

I’m trying to understand thread basics, and as a first example I create two

  • 0

I’m trying to understand thread basics, and as a first example I create two thread that write a String on the stdout. As I know the scheduler allows to execute the threads using a round robin schedule. Thats why I got:

PING
PING
pong
pong
pong
PING
PING
PING
pong
pong

Now I want to use a shared variable, so every thread will know if its your turn:

public class PingPongThread extends Thread {
private String msg;
private static String turn;

public PingPongThread(String msg){
    this.msg = msg;
}
@Override
public void run() {
    while(true) {
        playTurn();
    }

}
public synchronized void playTurn(){
    if (!msg.equals(turn)){
        turn=msg;
        System.out.println(msg);
    }
}
}

Main class:

public class ThreadTest {
    public static void main(String[] args) {
        PingPongThread thread1 = new PingPongThread("PING");
        PingPongThread thread2 = new PingPongThread("pong");
        thread1.start();
        thread2.start();
    }
}

I synchronized the “turn manager” but I still get something like:

PING
PING
pong
pong
pong
PING
PING
PING
pong
pong

Can someone explains what I am missing, and Why I’m not getting Ping pong… ping pong.
Thanks!

  • 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-12T13:10:24+00:00Added an answer on June 12, 2026 at 1:10 pm

    This line:

    public synchronized void playTurn(){
        //code
    }
    

    is equivalent in behavior to

    public void playTurn() {
        synchronized(this) {
             //code
        }
    }
    

    that’s why no synchronization is occuring, because as Brian Agnew pointed out, the threads are synchronizing on two different objects (thread1, thread2), each on it’s own instance resulting in no effective synchronization.

    If you would use your turn variable for synchronization, e.g.:

    private static String turn = ""; // must initialize or you ll get an NPE
    
    public void playTurn() {
        synchronized(turn) {
             //...
             turn = msg; // (1)
             //...
        }
    }
    

    then the situation is a lot better (run multiple times to verify), but there is also no 100% synchronization. In the beggining (mostly) you get a double ping and double pong, and afterwards they look synchronized, but you still can get double pings/pongs.

    The synchronized block locks upon value (see this great answer) and not the reference to that value. (see EDIT)

    So let’s take a look at one possible scenario:

    thread1 locks on ""
    thread2 blocks on ""
    thread1 changes the value of turn variable to "PING" - thread2 can continue since "" is no longer locked 
    

    To verify that I tried putting

    try {
        Thread.currentThread().sleep(1000); // try with 10, 100 also multiple times
     } 
     catch (InterruptedException ex) {}
    

    before and after

    turn = msg;
    

    and it looks synchronized?! But, if you put

     try {
        Thread.yield();
        Thread.currentThread().sleep(1000); //  also  try multiple times
     } 
     catch (InterruptedException ex) {}
    

    after few seconds you’ll see double pings/pongs. Thread.yield() essenitally means “I’m done with the processor, put some else thread to work”. This is obviously system thread scheduler implementation on my OS.

    So, to synchronize correctly we must remove line

        turn = msg;
    

    so that threads could always synchronize on the same value – not really 🙂 As explained in the great answer given above – Strings (immutable objects) are dangerous as locks – because if you create String “A” on 100 places in your program all 100 references(variables) will point to the same “A” in memory – so you could oversynchronize.

    So, to answer your original question, modify your code like this:

     public void playTurn() {
        synchronized(PingPongThread.class) {
             //code
        }
    }
    

    and the parallel PingPong example will be 100% correctly implemented (see EDIT^2).

    The above code is equivalent to:

     public static synchronized void playTurn() {
         //code
     }
    

    The PingPongThread.class is a Class object, e.g. on every instance you can call getClass() which always has only one instance.

    Also you could do like this

     public static Object lock = new Object();
    
     public void playTurn() {
        synchronized(lock) {
             //code
        }
    }
    

    Also, read and program examples(running multiple times whenever neccessary) this tutorial.

    EDIT:

    To be technically correct:

    The synchronized method is the same as synchronized statement locking upon this. Let’s call the argument of the synchronized statement “lock” – as Marko pointed out, “lock” is a variable storing a reference to an object/instance of a class. To quote the spec:

    The synchronized statement computes a reference to an object; it then attempts to perform a lock action on that object’s monitor..

    So the synchronizaton is not acutally made upon value – the object/class instance, but upon the object monitor associated with that instance/value. Because

    Each object in Java is associated with a monitor..

    the effect remains the same.

    EDIT^2:

    Following up on the comments remarks:
    “and the parallel PingPong example will be 100% correctly implemented” – meaning, the desired behavior is achieved (without error).

    IMHO, a solution is correct if the result is correct. There are many ways of solving the problem, so the next criteria would be simplicity/elegance of the solution – the phaser solution is better approach, because as Marko said in other words in some comment there is a lot lesser chance of making error using phaser object than using synchronized mechanism – which can be seen from all the (non)solution variants in this post. Notable to see is also comparison of code size and overall clarity.

    To conclude, this sort of constructs should be used whenever they are applicable to the problem in question.

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

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
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 have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
Does anyone know how can I replace this 2 symbol below from the string
i got an object with contents of html markup in it, for example: string
I'm trying to use string.replace('’','') to replace the dreaded weird single-quote character: ’ (aka

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.