我设置了一个计时器并在计时器中(在它完成任务之前和计数期间)我希望它打印我输入的内容,并在计时器完成计数后(当它准备好时)做任务)我希望它完成寻找输入(Scanner.nextline()),基本上要求它结束Scanner.nextline。当我尝试在计时器上使用.isAlive时,它给了我一个错误,即使我导入(我认为是)所有必要的类,它也找不到符号。
package javaapplication1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.text.DecimalFormat;
import java.math.*;
import java.lang.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author Morgan Higginbotham
*/
public class JavaApplication1 extends Thread {
public static void main(String[] args){
Scanner ci = new Scanner(System.in);
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Next");
}
};
Timer t=new Timer();
t.schedule(task, 1000);
while (t.isAlive()) { //not sure what to put in my while statement
//while the timer is counting
System.out.println(ci.nextLine());
}
//when the timer is done counting and ready to do the task
}
}
答案 0 :(得分:0)
看起来你想重复打印一些东西,直到另一个线程完成它的东西。你不能用Timer做到这一点,没有isAlive()
或类似的方法。
相反,您可以使用线程池和未来:
private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);
在你的方法中:
MyTask task = new MyTask();
Future future = threadpool.submit(task);
while (!future.isDone()) {
System.out.println("Task is not completed yet....");
Thread.sleep(1); //sleep for 1 millisecond before checking again }
}
班级MyTask
需要实施Callable
:
public class MyTask implements Callable {
public Object call() {
//do stuff in thread
}
}