我需要在预定义的时间内运行一些代码,当时间到了需要停止时.目前我正在使用TimerTask来允许代码执行一段时间,但这会导致代码创建无穷无尽的线程,而这只是效率不高.还有更好的选择吗?
当前代码;
// Calculate the new lines to draw
Timer timer3 = new Timer();
timer3.schedule(new TimerTask(){
public void run(){
ArrayList<String> Coords = new ArrayList<String>();
int x = Float.valueOf(lastFour[0]).intValue();
int y = Float.valueOf(lastFour[1]).intValue();
int x1 = Float.valueOf(lastFour[2]).intValue();
int y1 = Float.valueOf(lastFour[3]).intValue();
//Could be the wrong way round (x1,y1,x,y)?
Coords = CoordFiller.coordFillCalc(x, y, x1, y1);
String newCoOrds = "";
for (int j = 0; j < Coords.size(); j++)
{
newCoOrds += Coords.get(j) + " ";
}
newCoOrds.trim();
ClientStorage.storeAmmendedMotion(newCoOrds);
}
}
,time);
Run Code Online (Sandbox Code Playgroud) 任何人都可以在java中为我提供一个很好的小例子演示wait()和notify()功能.我试过下面的代码,但它没有显示我的预期.
public class WaitDemo {
int i = 10;
int display() {
System.out.println("Lexmark");
i++;
return i;
}
}
Run Code Online (Sandbox Code Playgroud)
public class ClassDemo1 extends Thread {
private WaitDemo wd = new WaitDemo();
public static void main(String[] args) {
ClassDemo1 cd1 = new ClassDemo1();
ClassDemo1 cd2 = new ClassDemo1();
cd1.setName("Europe");
cd2.setName("America");
cd1.start();
cd2.start();
}
synchronized void display() {
System.out.println("Hello");
notifyAll();
}
public void run() {
synchronized (this) {
try {
{
notify();
System.out.println("The thread is " + currentThread().getName());
wait();
System.out.println("The value is " …Run Code Online (Sandbox Code Playgroud)