Each thread is associated with an instance of the Thread class. There are three main ways to define and start a thread: provide a Runnable object, subclass Thread, or use an Executor interface. The Runnable interface represents a task that can be executed by a thread and defines a run method with no arguments. Starting the thread causes the run method to be called in a separately executing thread. Runnable objects are more general than subclassing Thread because they can implement interfaces other than Thread. However, subclassing Thread is easier for simple applications. The Executor interface provides a way to decouple task submission from how the tasks are scheduled and run. Thread.sleep causes the current thread to suspend execution for a specified period,
2. Defining and Starting a Thread
Three ways
● Provide a Runnable object.
● Subclass Thread.
● Using Executor Interface
3. public interface Runnable
The Runnable interface should be implemented by any class whose
instances are intended to be executed by a thread. The class must
define a method of no arguments called run.
void run( )
starting the thread causes the object's run method to be called in
that separately executing thread.
6. Extending Thread class
The Thread class itself implements Runnable, though its run method
does nothing. An application can subclass Thread, providing its own
implementation of run method.
10. Runnable vs. Thread
● Runnable object, is more general, because the Runnable object can
subclass a class other than Thread.
● Sub-classing Thread is easier to use in simple applications or Testing
code , but is limited by the fact that your task class must be a
descendant of Thread
11. Thread scheduling
How each task will be run, including details of thread use, scheduling,
etc.
This code need to be seprated from the
instantiating thread class.
12. a way of decoupling task submission from the mechanics of
how each task will be run.
Task submission
The Executor will provide the mechanics of how Task will be executed.
15. The best approach is to separate the Runnable from the execution task
and it is compulsory for large-scale applications.
16. Pausing Execution with Sleep
Thread.sleep causes the current thread to suspend execution for a
specified period.
This is an efficient means of making processor time available to the other
threads of an application.
19. Two overloaded versions of sleep are provided
● sleep time = millisecond
● sleep time = nanosecond
However, these sleep times are not guaranteed to be precise, because
they are limited by the facilities provided by the underlying OS.