Java 查找线程的实例
我想知道某个线程的实例是否正在运行,这样我就可以使用它了。这可能吗?我该怎么做?有什么策略或建议吗 例如,假设我有以下线程:Java 查找线程的实例,java,android,multithreading,Java,Android,Multithreading,我想知道某个线程的实例是否正在运行,这样我就可以使用它了。这可能吗?我该怎么做?有什么策略或建议吗 例如,假设我有以下线程: public class SomeThread extends Thread{ ArrayList<String> stringArray=new ArrayList<String>(); public void run(){ //some long time operation or messaging goi
public class SomeThread extends Thread{
ArrayList<String> stringArray=new ArrayList<String>();
public void run(){
//some long time operation or messaging going on
}
public ArrayList<String> getList(){
return stringArray;
}
}
public abstract class AnyActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(//any an instace of SomeThread exist){
ArrayList<String> array=//somehow.getList();
} else {
SomeThread thread=new SomeThread();
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
}
public类SomeThread扩展线程{
ArrayList stringArray=新的ArrayList();
公开募捐{
//一些长时间的操作或消息正在进行
}
公共ArrayList getList(){
返回字符串数组;
}
}
公共抽象类活动{
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
如果(//存在SomeThread的任何instance){
ArrayList数组=//.getList();
}否则{
SomeThread线程=新的SomeThread();
线程设置优先级(线程最大优先级);
thread.start();
}
}
编辑1:我不想传递该线程的引用,因为这可能是我启动它的唯一地方。考虑到SomeThread具有重要意义并从应用程序开始。我需要通过Messenger
请求它做些什么,或者它可能会告诉活动以同样的方式做些什么。我已经更新了示例代码并设置AnyActivity抽象。应用程序中的所有活动都扩展了这个类,所以我不知道线程是否已经创建和启动,这意味着我不能依赖引用
因此,我无法使用
thread.isAlive()
,也没有静态方法SomeThread.isAlive()
。我可以在线程内部使用setName()
,但我以后如何通过其名称找到它?您需要将感兴趣的线程引用传递给您的代码,然后使用以下方法进行测试:
Thread t; t.isAlive();
另外,你可以告诉use你想做什么,也许我们可以帮你更多。thread.isAlive()
是你的朋友:试试这个
您还可以通过名称或id获取线程
)方法在运行时返回true,否则返回false找到解决方案,感谢您的指导
private SomeThread getSomeThread(){
Thread thread=null;
int i=0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
while(thread==null && i<threadArray.length){
if(threadArray[i].getName().equals(SomeThread.class.getSimpleName()))
thread=threadArray[i];
i++;
}
return (SomeThread)thread;
}
private SomeThread getSomeThread(){
线程=空;
int i=0;
Set threadSet=Thread.getAllStackTraces().keySet();
Thread[]threadArray=threadSet.toArray(新线程[threadSet.size()]);
当(thread==null&&i查看我无法传递引用时,我已经更新了我的问题,你能检查一下吗?
private SomeThread getSomeThread(){
Thread thread=null;
int i=0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
while(thread==null && i<threadArray.length){
if(threadArray[i].getName().equals(SomeThread.class.getSimpleName()))
thread=threadArray[i];
i++;
}
return (SomeThread)thread;
}