我想知道我怎么知道一个线程是否正在睡觉.我搜索了一下,我收集了一些信息,形成了我写的一个方法 isSleeping():boolean 我认为我可以在一个类中确定线程是否正在休眠.我只是想知道我可能错过了什么.注意:我没有经验0天的经验.
//isSleeping returns true if this thread is sleeping and false otherwise.
public boolean isSleeping(){
boolean state = false;
StackTraceElement[] threadsStackTrace = this.getStackTrace();
if(threadsStackTrace.length==0){
state = false;
}
if(threadsStackTrace[0].getClassName().equals("java.lang.Thread")&&
threadsStackTrace[0].getMethodName().equals("Sleep")){
state = true;
}
return state;
}
Run Code Online (Sandbox Code Playgroud) 我很抱歉这太长了,而且可能看起来太多了,但如果你能一目了然地弄清楚什么是错的,请告诉我.
在这个程序中,我尝试在每次获取一个令牌时从键盘输入一些单词(短语)并将其分配给一个对象sharedStorer(然后打印指定的值以跟踪输入内容,因为我有一个单独的输入字链) .这是由一个线程完成(类的主题Retriever,其implements Runnable)
还有另一个线程class TokenReader读取值sharedStorer并将其打印出来.TokenReader等待Retriever输入,当Retriever尝试输入时TokenReader尚未读取前一个令牌Retriever等待.
我的问题是,最后TokenReader等待永远Retriever完成其任务,因此程序永远不会终止.
这是我用来执行所需任务的所有4个类(和1个接口).
package Multithreads;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExerciseTest {
public static void main(String[] args) {
ExecutorService app=Executors.newFixedThreadPool(2);
Storer st=new SyncStorer();
System.out.println("Operation performed\t\t Value");
try{
app.execute(new Retriever(st));
app.execute(new TokenReader(st));
}catch(Exception e){
e.printStackTrace();
}
app.shutdown();
}
}
Run Code Online (Sandbox Code Playgroud)
package Multithreads;
public interface Storer {
public void set(String token);
public String …Run Code Online (Sandbox Code Playgroud)