我有一个方法,我想通过调用该方法来运行一个线程。但我可以运行一个线程。但现在我的问题是,即使我多次调用该方法,我也希望我的线程能够运行。例如,我正在调用一个方法,该方法调用线程方法并开始运行。现在我再次调用该方法,这不应导致线程先运行,而不会影响之前运行的线程。我想到使用Thread.isAlive();。但还是卡住了。
class MyRunnableThread implements Runnable{
public static int myCount = 0;
public MyRunnableThread(){
}
public void run() {
while(MyRunnableThread.myCount <= 10){
try{
System.out.println("Expl Thread: "+(++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex) {
System.out.println("Exception in thread: "+iex.getMessage());
}
}
}
}
public class RunMyThread {
public void call(){
System.out.println("Starting Main Thread...");
MyRunnableThread mrt = new MyRunnableThread();
Thread t = new Thread(mrt);
t.start();
while(MyRunnableThread.myCount <= 10){
try{
System.out.println("Main Thread: "+(++MyRunnableThread.myCount));
Thread.sleep(100);
} catch (InterruptedException iex){
System.out.println("Exception in main thread: "+iex.getMessage());
}
}
System.out.println("End of Main Thread...");
}
}
public void CallThreadCaller()
{
call();
}
现在我再次调用 call() 方法并且 它不应该影响之前运行的线程。它应该检查它是否正在运行或者应该启动线程。但是如果我们启动一个新实例,如何检查线程是否已经在运行。
最佳答案
如果您使用 Java 1.7,您应该做的是使用 ExecutorService
即 Executors.newSingleThreadExecutor()
。
这只有一个带有无界队列的 Activity 线程。因此,您对方法调用的后续调用将排队。
private ExecutorService ex = Executors.newSingleThreadExecutor();
public void yourMethod() {
ex.submit(new Runnable() {
public void run() {
// Your logic
}
});
}
现在,即使您多次调用yourMethod
,第一个线程也必须在后续线程启动之前完成。
关于java - 如何让线程不间断地运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33428960/