Domanda

Possible Duplicate:
Java String.equals versus ==

I am writing a program to simulate the hare and turtle race! I am using getName() to see which objects thread is executing and based on that i increment the objects value. This is my code:

public void run()
{
    try{
    for(int i=0;i<100;i++)

    {
                System.out.println(Thread.currentThread().getName());
        if(Thread.currentThread().getName() == "HARE")
        {

            hare++;
            System.out.println("hare thread");
            Thread.sleep(100);
            if(hare ==  49) 
            {
                Thread.sleep(2000);
            }   
        }
        if(Thread.currentThread().getName() == "TURTLE")
        {
            turtle++;
            Thread.sleep(250);  
        System.out.println("Turtle Thread");

        }

The problem is that even thought it detects the name of the thread accurately but it never goes inside the if block. P.S I am new to java multithreading. Thank you for going through the code.

È stato utile?

Soluzione

Thread.currentThread().getName() == "HARE"

you can not compare string in this way.

Thread.currentThread().getName().equals("HARE");

the equals method is case sensitive.

Altri suggerimenti

You need to use .eqauls() instead of == while comparing strings/objects.

So, your code should be something like below:

Thread.currentThread().getName().equals("HARE")

== compares for reference equality, that means both references point to same object or not. equals() method does content eqaulity, in other words checks Strings are same or not (Which is the one you required).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top