Java’s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. We can not directly refer to the ethereal (n. heavenly) state of a running thread, we should deal with it through its proxy, the thread instance that produced it. To create a new thread our program will either extend Thread or implement the Runnable interface.
To start the execution of a thread, we should call the start( ) method for the Thread object. The code that executes in a new thread is always a method called run( ), which is declared like:public void run( ) . Threads other than the main thread in a program always start in the run( ) method for the object that represents the thread. But here is a problem; we are unable to call run method to start a thread, we should call the start( ) method for the object representing the thread and that causes the run( ) method to be called. When we want to stop the execution of a thread that is running, we should call the stop( ) (now depricated) method for the Thread object. This is because, the threads are always run and managed by operating system and a new thread can only be created and started by the operating system. If we were to call run( ) method ourselves, it would simply operate like any other method, running in the same thread as the program that calls it. When we call the start( ) method for a thread object, we are calling a native code method that causes the operating system to initiate another thread from which the run( ) method for the thread object executes. Hence we should start our thread by calling the start( ) method.
No comments:
Post a Comment