Home  >  Article  >  Java  >  Java development: How to use multi-threading to implement concurrent task processing

Java development: How to use multi-threading to implement concurrent task processing

WBOY
WBOYOriginal
2023-09-21 15:03:31634browse

Java development: How to use multi-threading to implement concurrent task processing

Java development: How to use multi-threading to implement concurrent task processing

Introduction:
In modern software development, efficient concurrent task processing is crucial . In Java, multithreading is a common and powerful way to implement concurrent task processing. This article will introduce you to how to use multithreading to implement concurrent task processing, with specific code examples.

  1. Basic way to create a thread
    In Java, you can create a thread by inheriting the Thread class or implementing the Runnable interface. The following is sample code for two methods:

Method 1: Inherit the Thread class

public class MyThread extends Thread {
    public void run() {
        // 在这里写入线程运行时需要执行的代码
    }
}

// 创建并启动线程
MyThread myThread = new MyThread();
myThread.start();

Method 2: Implement the Runnable interface

public class MyRunnable implements Runnable {
    public void run() {
        // 在这里写入线程运行时需要执行的代码
    }
}

// 创建并启动线程
Thread thread = new Thread(new MyRunnable());
thread.start();
  1. Use the thread pool Managing threads
    In actual applications, directly creating threads may cause a waste of system resources. For better thread management, thread pools can be used. Java provides the ThreadPoolExecutor class, which can easily create a thread pool and manage the threads in it. The following is a sample code using a thread pool:
ExecutorService executorService = Executors.newFixedThreadPool(5); // 创建线程池,指定线程数量为5

for (int i = 0; i < 10; i++) {
    executorService.execute(new MyRunnable()); // 提交任务给线程池执行
}

executorService.shutdown(); // 关闭线程池

In the above sample code, we create a thread pool with a fixed size of 5. Then, we submit 10 tasks to the thread pool for execution in a loop. Finally, we call the shutdown() method to shut down the thread pool.

  1. Implementing communication between concurrent tasks
    It is often very important to implement communication between threads. Java provides a variety of ways to implement communication between threads, the most common of which are using shared variables and the wait() and notify() methods.

Use shared variables:

public class SharedData {
    private int count;

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

    public synchronized int getCount() {
        return count;
    }
}

SharedData sharedData = new SharedData();

// 创建并启动多个线程
for (int i = 0; i < 10; i++) {
    Thread thread = new Thread(() -> {
        sharedData.increment();
    });
    thread.start();
}

// 等待所有线程执行完毕
Thread.sleep(1000);

System.out.println(sharedData.getCount()); // 输出结果应为10

Use wait(), notify() methods:

public class Message {
    private String content;
    private boolean isEmpty = true;

    public synchronized String take() {
        while (isEmpty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isEmpty = true;
        notifyAll();
        return content;
    }

    public synchronized void put(String content) {
        while (!isEmpty) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isEmpty = false;
        this.content = content;
        notifyAll();
    }
}

Message message = new Message();

// 创建并启动多个线程
Thread producerThread = new Thread(() -> {
    for (int i = 0; i < 10; i++) {
        message.put("Message " + i);
        Thread.sleep(1000);
    }
});

Thread consumerThread = new Thread(() -> {
    for (int i = 0; i < 10; i++) {
        System.out.println(message.take());
        Thread.sleep(1000);
    }
});

producerThread.start();
consumerThread.start();
  1. Synchronization control between threads
    Multiple threads Concurrent execution may lead to thread safety problems. In order to avoid problems, we can use the synchronized keyword, Lock interface, etc. to synchronize key code. The following is an example of using the synchronized keyword:
public class Counter {
    private int count = 0;

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

    public synchronized void decrement() {
        count--;
    }

    public synchronized int getCount() {
        return count;
    }
}

Counter counter = new Counter();

// 创建并启动多个线程
Thread incrementThread = new Thread(() -> {
    for (int i = 0; i < 1000; i++) {
        counter.increment();
    }
});

Thread decrementThread = new Thread(() -> {
    for (int i = 0; i < 1000; i++) {
        counter.decrement();
    }
});

incrementThread.start();
decrementThread.start();

incrementThread.join();
decrementThread.join();

System.out.println(counter.getCount()); // 输出结果应为0

Conclusion:
Using multi-threading can effectively achieve concurrent task processing. In this article, we introduce how to create threads, use thread pools, implement communication between threads, and synchronize control between threads, and provide specific code examples. I hope these contents will be helpful to you in using multi-threading to implement concurrent task processing in Java development!

The above is the detailed content of Java development: How to use multi-threading to implement concurrent task processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn