Examples:
-
Thread Creation:
- Use
Runnable
interface for thread creation to promote better design.
- Use
class MyRunnable implements Runnable {
public void run() {
// Your thread logic here
}
}
Thread myThread = new Thread(new MyRunnable());
myThread.start();
-
Thread Safety:
- Synchronize critical sections to avoid data inconsistency.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
-
Thread Join:
- Use
join()
to wait for a thread to finish its execution.
- Use
Thread t1 = new Thread(() -> {
// Your thread logic
});
t1.start();
t1.join(); // Main thread waits for t1 to finish
-
Thread Pools:
- Utilize
ExecutorService
for managing thread pools.
- Utilize
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(new MyRunnable());
}
executor.shutdown();
-
Atomic Operations:
- Use
Atomic
classes for atomic operations to avoid race conditions.
- Use
AtomicInteger atomicInt = new AtomicInteger(0);
atomicInt.incrementAndGet();
-
Thread Interruption:
- Gracefully handle thread interruption.
while (!Thread.interrupted()) {
// Your thread logic
}
-
Thread Local:
- Utilize
ThreadLocal
for thread-specific data.
- Utilize
ThreadLocal<SimpleDateFormat> dateFormat = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
String formattedDate = dateFormat.get().format(new Date());
-
Thread Priority:
- Use thread priority cautiously, as it may not be honored on all platforms.
myThread.setPriority(Thread.MAX_PRIORITY);
-
Volatile Keyword:
- Use
volatile
keyword for variables accessed by multiple threads to ensure visibility.
- Use
private volatile boolean flag = false;
-
ExecutorService Shutdown:
- Gracefully shut down the
ExecutorService
.
executor.shutdown(); try { if (!executor.awaitTermination(500, TimeUnit.MILLISECONDS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); }
- Gracefully shut down the
Remember to handle exceptions, and always be mindful of potential deadlock situations when working with threads in Java.
Read more Visit git repository
https://github.com/Pankaj-Str/Learn-JAVA-SE/tree/main/Day_59_Threading
Top comments (1)