• Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads and sleep()  RSS feed

 
Phil Hopgood
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've been playing with (oops, learning about) threading and I've got the following code but it doesn't seem do what I expected it to:





Please ignore the cack-handed way of doing the time stamp I just wanted to see what was going on.

I get the following output:


27:30:296: In main, start myThread1
27:30:296: myThread1 sleeping for 10000
27:30:296: Starting Thread: 1
27:30:306: Starting Thread: 1 is sleeping for 2000
27:32:309: Thread: 1 awake now, Top o' the stack Ma!
27:40:301:back in main ...... am I?
27:40:301: Starting Thread: 2
27:40:301: Starting Thread: 2 is sleeping for 2000
27:42:303: Thread: 2 awake now, Top o' the stack Ma!


So what seems to happen is that main runs doing:
27:30:296: In main, start myThread1
27:30:296: myThread1 sleeping for 10000

Thread 1 then runs:
27:30:296: Starting Thread: 1
27:30:306: Starting Thread: 1 is sleeping for 2000

thread 1 sleeps for 2 secs:

27:32:309: Thread: 1 awake now, Top o' the stack Ma!

Main runs after another 8 secs making 10 in all:
27:40:301:back in main ...... am I?

then thread 2 runs with a 2 second sleep:
27:40:301: Starting Thread: 2
27:40:301: Starting Thread: 2 is sleeping for 2000
27:42:303: Thread: 2 awake now, Top o' the stack Ma!

So my questions are:
1. What effect does myThread1.sleep(10000); have? I expected thread 1 to sleep for 2 secs AND 10 secs the order being determined by when the jvm decided it should swap the threads about.

2. I put a big sleep in (sorry Raymond) to see if thread 2 or main would get a look in while thread 1 was asleep but this doesn't seem to be happening. So what is happening? Nothing happens while thread 1 is asleep. I'm confused.

I hope the above is clear.

Thanks for you time and help.
Regards,
Phil.
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sleep() affects the calling thread. In fact, the method is static as it doesn't need any details from the thread object -- it is the current thread, the calling thread, that is going to sleep.

Henry
 
Phil Hopgood
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry,

Aaaaaaah, that accounts for it! How silly of me.

Thanks for your prompt reply Henry.

Regards,
Phil.
 
Ove Lindström
Ranch Hand
Posts: 326
Android Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just for comfort Phil. I've been hacking Java for quite some time now and I STILL does that same misstake now and then...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!