相关疑难解决方法(0)

在一段时间内运行代码的更好方法

我需要在预定义的时间内运行一些代码,当时间到了需要停止时.目前我正在使用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 timertask

8
推荐指数
1
解决办法
2万
查看次数

一个很好的小例子来演示java中的wait()和notify()方法

任何人都可以在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)

java multithreading notify wait

8
推荐指数
1
解决办法
3万
查看次数

标签 统计

java ×2

multithreading ×1

notify ×1

timertask ×1

wait ×1