views:

99

answers:

2

Hello everyone,

I have the following code in my program:

Thread getUsersist, getChatUsers;

getUsersList = new Thread(this, "getOnlineUsers");
getUsersList.start();
getChatUsers = new Thread(this, "getChatUsers");
getChatUsers.start();

In run(), I wish to know which thread is using run(). If its "getOnlineUsers" i will do something, If it is "getChatUsers" I will do something else. So how do I know which thread is using run()?

+10  A: 

In run(), you can do:

Thread.currentThread().getName()

to get either "getOnlineUsers" or "getChatUsers" and take a different code path accordingly. That said, it seems like a rather fragile design to me and I'd imagine you'd be far better off with separate classes for each thread.

HTH,
Kent

Kent Boogaart
You don't need `Thread.currentThread()`. `run()` is a method of the Thread class descendant.
Marcelo Cantos
But it's a `Runnable` not a `Thread`
Sean Owen
+1 for noting this approach is sketchy and better alternatives should be considered.
Martinho Fernandes
@Marcelo: But the run() method of Runnable is not.
Thilo
+1: "separate classes for each thread": or at least a property on the Runnable.
Thilo
yup, I am implementing Runnable. And this method works, unlike Marcelo's although I dont understand why.
mithun1538
+1. Silly me...
Marcelo Cantos
+3  A: 
if (getName().equals("getOnlineUsers")) {
    doOneThing();
else if (getName().equals("getChatUsers")) {
    doAnotherThing();
} else {
    throw Up();
}

EDIT: Ignore this answer. Read the accepted answer.

Marcelo Cantos
But the `this` in his code example is a `Runnable`, not a `Thread`. `getName()` is not available.
Sean Owen
I tried this, but simply doing System.out.println(getName()) gives me some other thread name, not the one that I need("getOnlineUsers","getChatUSers").
mithun1538