Always there’s a Thread executing code. Even in a program where you don’t create threads there’s the main thread that runs the program. We use static method Thread.currentThread() to access name of Thread running current code. If it is called in the main thread then it returns it. If it is called withing code executed by some other thread, then that thread is returned. See program output and it will be immediately clear. ;-)

We print the thread’s name to show which thread currently executes that line of code. As you can see simply calling Runnable.run() doesn’t start a new thread and is just a simple method call – like it would be any other class. To execute that code in another thread we have to call start() method on Thread. It allocates resources for a new thread and executes Runnable.run() for us. Note that in the output after “Thread.start()” the thread’s name has changed to counter-thread.

Very important thing to note is that the new thread’s code can run in unpredictable order. Note that in the output “End of main()” appears before Counter’s output, which has been called sooner.

In the subsequent posts will dig into Java concurrency, so stay tuned. :-)