Creating Threads:
Extending Thread Class: A class can extend the Thread class and override
its run() method to define the thread's execution logic.
class MyThread extends Thread {
public void run() {
// Thread's execution logic
Implementing Runnable Interface: A class can implement the Runnable interface
and define its run() method. An instance of this class can then be passed to
a Thread constructor. This is generally preferred as it allows the class to extend
other classes.
class MyRunnable implements Runnable {
public void run() {
// Thread's execution logic
// In main:
// Thread t = new Thread(new MyRunnable());
// [Link]();
. Starting Threads:
The start() method of a Thread object is called to begin its execution. This
method creates a new execution stack and invokes the run() method in that new
thread of control.
3. Synchronization with synchronized Methods:
Purpose:
When multiple threads access and modify shared resources (like variables or
objects), race conditions and data inconsistency can occur. Synchronization
prevents this by ensuring that only one thread can access a critical section of code
at a time.
synchronized Keyword:
Applying the synchronized keyword to a method ensures that only one thread
can execute that method on a given object instance at any time. When a thread
enters a synchronized method, it acquires an intrinsic lock on the object. Other
threads attempting to enter any synchronized method on the same object will be
blocked until the lock is released (when the first thread exits
the synchronized method).
class SharedResource {
private int count = 0;
public synchronized void increment() {
count++; // This operation is now thread-safe
public synchronized int getCount() {
return count;
Static synchronized Methods: When a static method is declared synchronized,
the lock is acquired on the Class object itself, ensuring that only one thread can execute that
static synchronized method across all instances of that class.
In summary: Threads provide concurrency, while the synchronized keyword, particularly
on methods, ensures thread safety when multiple threads interact with shared resources,
preventing data corruption and maintaining consistency.