如何让程序等到计时器线程完成后再继续?

我正在做一个学习java的小程序,我想打印一些东西,等待几秒钟(通过打印显示......)然后继续该程序。我通过使用Timer和做到了这一点TimerTask。我想知道如何让程序的执行等到我的计时器线程结束。


我尝试timer.wait()在某些地方添加但不起作用。


public class Main

{

    public static void main(String[] args)

    {

        System.out.println("text1");

        clock currentClock = new clock();

        currentClock.run();

        // i want the program to stop until this is over, adding currentClock.wait(); doesnt work

        System.out.println("text2");

    }

}


class clockHelper extends TimerTask

{ // printing class, called by clock class


    int actual = 0;


    public void run()

    {

        if (actual < 3)

        {

            System.out.println(".");

            actual++;

        } else

        {

            cancel();

        }

    }

}


class clock

{ // called by main class

    public static void run()

    {


        Timer watch = new Timer();

        TimerTask timer2 = new clockHelper();

        watch.schedule(timer2, 1000, 500);

        // adding watch.wait(); doesn't work, i can also stop it here and it should work fine

    }

}

这是我得到的错误:java.lang.IllegalMonitorStateException


我想要的结果是打印这个:“text”。。。“文本2”


如果我删除wait(这会导致错误),则会打印: "text1" "text2" 。。。


在此先感谢您的任何信息。


子衿沉夜
浏览 122回答 1
1回答

慕哥9229398

你可以这样做:public class Main{&nbsp; &nbsp; public static void main(String[] args) throws InterruptedException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("text1");&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 3; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(".");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Thread.sleep(1000);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("text2");&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java