How to work with threads in Java

Threads are a powerful tool for concurrent programming in Java. In this post, we will explore how to work with threads in Java.

Creating a thread

In Java, a thread is represented by an instance of the Thread class. To create a new thread, we can either extend the Thread class and override its run() method, or implement the Runnable interface and pass an instance of our implementation to a new Thread instance. Here’s an example of each approach:

// Extending the Thread class
public class MyThread extends Thread {
    public void run() {
        // Code to execute in the thread
    }
}

// Implementing the Runnable interface
public class MyRunnable implements Runnable {
    public void run() {
        // Code to execute in the thread
    }
}

// Creating a new thread
Thread thread1 = new MyThread();
Thread thread2 = new Thread(new MyRunnable());

In the above code, we created a new thread by extending the Thread class in MyThread and implementing the Runnable interface in MyRunnable. We then created instances of these classes and passed them to new Thread instances.

Starting and joining threads

To start a thread, we call its start() method. This method launches a new thread and calls the run() method on the thread instance. Here’s an example:

Thread thread = new MyThread();
thread.start();

To wait for a thread to finish executing, we can call its join() method. This method blocks the calling thread until the target thread has finished executing. Here’s an example:

Thread thread = new MyThread();
thread.start();
thread.join();

In the above code, we created a new thread and called its join() method to wait for it to finish executing.

Thread synchronization

When multiple threads access shared resources, we need to ensure that they do so safely to avoid race conditions and other synchronization issues. In Java, we can use the synchronized keyword to ensure that only one thread at a time can access a block of code or an object.

public class MyThread implements Runnable {
    private int counter = 0;

    public synchronized void increment() {
        counter++;
    }

    public void run() {
        for (int i = 0; i < 1000; i++) {
            increment();
        }
    }

    public int getCounter() {
        return counter;
    }
}

// Creating multiple threads
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread);
Thread thread2 = new Thread(myThread);

// Starting the threads
thread1.start();
thread2.start();

// Waiting for the threads to finish
thread1.join();
thread2.join();

// Getting the result
System.out.println("Counter: " + myThread.getCounter());

In the above code, we created a new MyThread class with a synchronized increment() method that increments a counter. We then created multiple threads that each call the increment() method, and waited for them to finish executing. Finally, we printed the result of the counter.

Conclusion

In this post, we learned how to work with threads in Java. We covered how to create a new thread, start and join threads, and synchronize threads to avoid race conditions. With this knowledge, you can start building Java applications that use threads for concurrent programming.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *