Java:while循环中的Thread.sleep()无法正常工作 [英] Java: Thread.sleep() inside while loop not working

查看:1290
本文介绍了Java:while循环中的Thread.sleep()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我是线程技术的新手,所以我的问题可能很愚蠢.但是我想问的是,我有一个此类,假设它的名称是MyClass.java.然后在其方法之一内是callThread(),我想将其打印出来,进行睡眠,然后将控制权返回给MyClass.java的方法.我该怎么办?

Alright, I'm new to threading, so my question might be pretty dumb. But what I want to ask is, I have this class, let's say its name is MyClass.java. And then inside one of its methods is callThread(), which I want to print something out, sleep, and return control to MyClass.java's method. How do I do that?

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

Currently, my code goes something like this:

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

然后,这将是MyThread:

And then, this will be the MyThread:

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

我希望MyThread可以打印"hi",将控制权传递回MyClass,然后在一秒钟后再次打印"hi".相反,MyThread冻结了我的整个程序,因此根本无法使用它.

I was hoping that MyThread would print "hi", pass back control to MyClass, and then print "hi" again one second later. Instead, MyThread freezes up my entire program so having it in there doesn't work at all...

有什么办法解决这个问题吗?

Is there any way around this?

推荐答案

您应该是callig thread.start()

You should be callig thread.start()

有关该手册的更多信息:定义和启动线程

More on that in the manual: Defining and Starting a Thread

这篇关于Java:while循环中的Thread.sleep()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆