Basic overview on working with threads in Java:

Category : Java | Sub Category : Java Threads | By Prasad Bonam Last updated: 2023-08-15 11:12:58 Viewed : 311


Threads in Java allow you to execute multiple tasks concurrently. Threads can be used to achieve parallelism and better utilization of system resources. Here is a basic overview on working with threads in Java:

1. Creating Threads: There are two main ways to create threads in Java: by extending the Thread class or by implementing the Runnable interface.

a. Extending Thread class:

java
class MyThread extends Thread { public void run() { // Code to be executed in the thread } } public class ThreadExample { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // Start the thread } }

b. Implementing Runnable interface:

java
class MyRunnable implements Runnable { public void run() { // Code to be executed in the thread } } public class ThreadExample { public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // Start the thread } }

2. Thread States: Threads in Java have various states, including NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED.

3. Thread Synchronization: Threads may need synchronization to avoid data inconsistency issues due to concurrent access. You can use synchronized blocks or methods to achieve synchronization.

java
class Counter { private int count = 0; public synchronized void increment() { count++; } } public class SynchronizationExample { public static void main(String[] args) { Counter counter = new Counter(); // Create multiple threads that increment the counter } }

4. Thread Priority: Threads can have different priorities ranging from 1 (lowest) to 10 (highest). You can set thread priorities using the setPriority() method.

5. Thread Joining: The join() method is used to wait for a thread to complete its execution before proceeding with the current thread.

java
Thread thread = new Thread(new MyRunnable()); thread.start(); thread.join(); // Wait for the thread to finish

6. Thread Pooling: Creating threads for every task can be inefficient. Java provides ExecutorService and ThreadPoolExecutor classes to manage a pool of threads for reuse.

java
ExecutorService executor = Executors.newFixedThreadPool(5); // Create a thread pool with 5 threads executor.execute(new MyRunnable()); // Execute a task in a thread from the pool executor.shutdown(); // Shut down the thread pool

These are the basics of working with threads in Java. Keep in mind that thread management, synchronization, and advanced concurrency concepts require careful consideration to ensure safe and efficient concurrent programming.


1. Creating Threads:

There are two main ways to create threads in Java:

a. Extending Thread Class:

java
class MyThread extends Thread { public void run() { System.out.println("Thread is running"); } } public class ThreadExample { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); // Starts the threads execution } }

b. Implementing Runnable Interface:

java
class MyRunnable implements Runnable { public void run() { System.out.println("Thread is running"); } } public class ThreadExample { public static void main(String[] args) { MyRunnable runnable = new MyRunnable(); Thread thread = new Thread(runnable); thread.start(); } }

2. Starting and Joining Threads:

After creating a thread, you start it using the start() method. To wait for a thread to finish, you can use the join() method.

java
public class ThreadJoinExample { public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Thread 1: " + i); } }); Thread thread2 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Thread 2: " + i); } }); thread1.start(); thread2.start(); thread1.join(); // Wait for thread1 to finish thread2.join(); // Wait for thread2 to finish System.out.println("Main thread is done"); } }

3. Synchronization:

When multiple threads access shared resources, synchronization is needed to avoid data inconsistency and race conditions.

java
class Counter { private int count = 0; public synchronized void increment() { count++; } public int getCount() { return count; } } public class SynchronizationExample { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }; Thread thread1 = new Thread(task); Thread thread2 = new Thread(task); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println("Final count: " + counter.getCount()); } }

This is just a basic introduction to Java threads. There is much more to explore, including thread synchronization, thread pools, and advanced topics like concurrency utilities. Always ensure proper synchronization and handle exceptions when working with threads to create robust and reliable multithreaded applications.

Search
Related Articles

Leave a Comment: