matt
matt

Reputation: 2997

Java: Thread.sleep() inside while loop not working

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...
    }
}

And then, this will be the MyThread:

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

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?

Upvotes: 3

Views: 20661

Answers (2)

Tomáš Plešek
Tomáš Plešek

Reputation: 1492

You should be callig thread.start()

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

Upvotes: 11

KV Prajapati
KV Prajapati

Reputation: 94645

You must have to call start() method of Thread class.

MyThread thread = new MyThread();
Thread th=new Thread(thread);
th.start();

sleep() is an instance method of Thread class and MyThread class is not a thread (It's a runnable) so you need to use Thread.currentThread().sleep() method.

while (true)
 {
     System.out.println("hi");
     try{
        Thread.currentThread().sleep(1000);
     }catch(Exception ex){ }
  }

Read this tutorial for more info on thread.

Upvotes: 4

Related Questions