开发者

how to differentiate between two threads

开发者 https://www.devze.com 2022-12-25 10:53 出处:网络
I have the following code in my program: Thread getUsersist, getChatUsers; getUsersList = new Thread(this, \"getOnlineUsers\");

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

精彩评论

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