Java: while 循环内的 Thread.sleep() 不起作用

2024-01-10

好吧,我是线程新手,所以我的问题可能很愚蠢。但我想问的是,我有这个类,假设它的名称是MyClass.java。然后它的方法之一是 callThread(),我想打印一些东西,休眠,并将控制权返回给 MyClass.java 的方法。我怎么做?

目前,我的代码是这样的:

class MyClass {
    void method()
    {
        MyThread thread = new MyThread();
        thread.run();
        // do some other stuff here...
    }
}

然后,这将是 MyThread:

class MyThread implements Runnable {
    public void run()
    {
        while (true)
        {
            System.out.println("hi");
            this.sleep(1000);
        }
    }
}

我希望 MyThread 能够打印“hi”,将控制权传回 MyClass,然后一秒钟后再次打印“hi”。相反,MyThread 冻结了我的整个程序,因此将其放在那里根本不起作用......

有没有办法解决?


你应该调用 thread.start()

手册中有更多相关内容:定义和启动线程 http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java: while 循环内的 Thread.sleep() 不起作用 的相关文章

随机推荐