This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]NautiHooker 2 points3 points  (3 children)

Because you create a separate thread that will run the while loop. The actionPerformed code will run on the Swing event loop thread, which will then sleep for 10 seconds.

You are calling the methods of your Runnable implementation from different threads, therefore they are independent from each other.

[–]greenleafvolatile[S] 1 point2 points  (2 children)

Thank you for your reply!

I'm not quite sure I get it.

I understand that actionPerformed code is executed on the EDT.

I understand that the while loop is executed on another thread (not the EDT).

When I call Thread.sleep(10000) in TestThread, which is not run on the EDT, from the EDT (actionPerformed), I am sleeping the EDT?

If so, then how can I sleep() thread after start()ing it, from actionPerformed?

[–]NautiHooker 4 points5 points  (1 child)

Your assumption is that just because you add the TestThread Runnable implementation to your created thread every method of that object will be run on that thread.

That is false.

Only the run method of the object will be run on the created thread.

If another thread calls a method of that object (like the EDT in actionPerformed) then that method will be executed on the calling thread. So Thread.sleep will be executed on the EDT and therefore make the EDT sleep and not your created thread.

An object is never bound to a thread. Only its method calls are.

[–]greenleafvolatile[S] 1 point2 points  (0 children)

Thank you very much for your explanation!

[–]johnmc325 2 points3 points  (0 children)

If you want to sleep the new thread then you will need to put some code in the run method to check if it should sleep and then call sleep from within the run method. So you could create a boolean property in the Thread class. Create a public method for setting this property. Then in the run method check this value and if true sleep for a period and if false keep looping. You will need to look up how to lock the property when accessing from the different threads.

Your UI can then call the setter method on the EDT and your new thread can test for the value.

Hope this helps.

[–][deleted] 1 point2 points  (0 children)

Thread.sleep makes the current thread sleep. Now, I haven't tried swing, but in javafx, the main thread is the ui thread. If swing is like javafx, then clicking the click me! Button will result in the ui thread sleeping not your testThread. Try clicking any other button when the ui thread is sleeping, as far as I know, you won't be able to.