How to achieve concurrency in Java?

Java can achieve concurrency through multithreading. Here are some common ways to implement concurrency.

  1. Use the Thread class: create a subclass that inherits from Thread class, override the run() method to define the thread’s execution logic. Then, create multiple thread instances and call the start() method to start the threads.
class MyThread extends Thread {
    public void run() {
        // 线程执行逻辑
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();

        thread1.start();
        thread2.start();
    }
}
  1. To use the Runnable interface, create a class that implements the interface, override the run() method to define the thread’s execution logic. Then, create multiple instances of Runnable and pass them as arguments to the constructor of the Thread class.
class MyRunnable implements Runnable {
    public void run() {
        // 线程执行逻辑
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable1 = new MyRunnable();
        MyRunnable runnable2 = new MyRunnable();

        Thread thread1 = new Thread(runnable1);
        Thread thread2 = new Thread(runnable2);

        thread1.start();
        thread2.start();
    }
}
  1. Using a thread pool: Create a thread pool through the Executor framework to manage and execute multiple tasks, enabling the reuse of threads and improving efficiency.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        executor.execute(new Runnable() {
            public void run() {
                // 任务1执行逻辑
            }
        });

        executor.execute(new Runnable() {
            public void run() {
                // 任务2执行逻辑
            }
        });

        executor.shutdown();
    }
}

These are three common ways to achieve concurrency, choose the most suitable method based on specific needs and scenarios. There are also more advanced concurrency control tools and techniques, such as locks, condition variables, and semaphores, which can be further studied and used as needed.

bannerAds