Prerequisites
There are principally two ways to create worker threads--by extending the java.lang.Thread
class and by implementing the java.lang.Runnable
interface. While extending the java.lang.Thread
class, we are not required to implement anything:
class MyThread extends Thread { }
Our MyThread
class inherits the name
property with an automatically generated value and the start()
method. We can run this method and check the name
:
System.out.print("demo_thread_01(): "); MyThread t1 = new MyThread(); t1.start(); System.out.println("Thread name=" + t1.getName());
If we run this code, the result will be as follows:
As you can see, the generated name
is Thread-0
. If we created another thread in the same Java process, the name
would be Thread-1
and so on. The start()
method does nothing. The source code shows that it calls the run()
method if such a method is implemented.
We can add any other method to the MyThread
class as follows:
class MyThread extends Thread { private...