Threads enable a program to operate more efficiently by executing multiple tasks concurrently.
They can handle complex operations in the background without disrupting the main program.
Two methods exist for creating a thread.
One approach involves extending the Thread class and overriding its run() method.
public |
An alternative method to create a thread is by implementing the Runnable interface.
public |
If a class extends the Thread class, the thread can be executed by creating an instance of the class and invoking its start() method.
public |
When a class implements the Runnable interface, the thread can be executed by passing an instance of the class to a Thread object’s constructor, followed by calling the start() method of the thread.
public |
Distinguish between “extending” and “implementing” Threads. The primary distinction is that when a class extends the Thread class, it precludes extending any other class. Conversely, by implementing the Runnable interface, it remains feasible to extend from another class, such as: class MyClass extends OtherClass implements Runnable. |
Since threads execute concurrently with other parts of the program, the order in which the code runs is unpredictable. When both threads and the main program access and modify the same variables, the resulting values become unpredictable. These issues stemming from concurrent access are referred to as concurrency problems.
An example code where the value of the variable “amount” becomes unpredictable:
public
|
To mitigate concurrency issues, it’s advisable to minimize the sharing of attributes between threads. If attributes must be shared, one potential solution is to utilize the isAlive() method of the thread to verify whether the thread has completed its execution before accessing any attributes that the thread might alter.
Leverage the isAlive() method to mitigate concurrency issues.
public
|