Java Threads
Threads in Java allow concurrent execution of two or more parts of a program to maximize the utilization of CPU. Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU.
1. Creating Threads
You can create a thread in Java in two ways:
- By extending the
Thread
class. - By implementing the
Runnable
interface.
1.1 Extending the Thread
Class
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running.");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
1.2 Implementing the Runnable
Interface
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running.");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
2. Thread Methods
start()
: Starts the thread by calling itsrun()
method.sleep(long milliseconds)
: Causes the thread to sleep for the specified time.join()
: Waits for the thread to die.getName()
andsetName(String name)
: Gets or sets the thread's name.
3. Thread Synchronization
Synchronization is used to control access to shared resources in multithreaded applications to prevent data inconsistency.
Example: Using the synchronized
Keyword
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
4. Thread Communication
Threads can communicate using methods like wait()
, notify()
, and notifyAll()
.
5. Key Takeaways
- Threads enable concurrent execution in Java.
- Create threads by extending
Thread
or implementingRunnable
. - Use synchronization to control access to shared resources.
- Be cautious of issues like deadlocks and race conditions.
- Proper thread management is crucial for application performance and reliability.