簡體   English   中英

如何區分兩個線程

[英]how to differentiate between two threads

我的程序中包含以下代碼:

Thread getUsersist, getChatUsers;

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

在run()中,我想知道哪個線程正在使用run()。 如果它是“ getOnlineUsers”,我會做一些事情;如果是“ getChatUsers”,我會做其他事情。 那么我怎么知道哪個線程正在使用run()呢?

run() ,您可以執行以下操作:

Thread.currentThread().getName()

獲取“ getOnlineUsers”或“ getChatUsers”並相應地采用其他代碼路徑。 也就是說,對我來說,這似乎是一個相當脆弱的設計,我想您會為每個線程使用單獨的類而變得更好。

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

編輯:忽略此答案。 閱讀接受的答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM