开发者

how to differentiate between two threads

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" 开发者_如何学GoI will do something else. So how do I know which thread is using run()?


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.


if (getName().equals("getOnlineUsers")) {
    doOneThing();
else if (getName().equals("getChatUsers")) {
    doAnotherThing();
} else {
    throw Up();
}

EDIT: Ignore this answer. Read the accepted answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜