Home  >  Article  >  Java  >  Multithreaded Programming in Java

Multithreaded Programming in Java

王林
王林Original
2023-06-09 12:13:471669browse

Multi-threaded programming in Java

Java is a programming language widely used in the field of software development, and multi-threaded programming is a common programming model in Java. Multi-threaded programming can enable a program to perform multiple tasks at the same time, improving the concurrency and efficiency of the program. This article will introduce you to multi-threaded programming in Java.

The basic concept of multi-threading

Multi-threading refers to the ability of a program to perform multiple tasks at the same time. In the case of a single-core CPU, multithreading is achieved by the CPU quickly switching between different tasks. In the case of multi-core CPUs, multiple tasks can be executed simultaneously on different CPU cores.

Multi-threading implementation in Java

Multi-threading in Java is achieved by creating objects of the Thread class, which provides a lightweight thread implementation. Threads can be created by inheriting the Thread class or implementing the Runnable interface.

  1. Inherit the Thread class

Inheriting the Thread class is the simplest way to implement it. You only need to create a class and inherit the Thread class, and override the run() method to achieve it. Multi-threading capabilities. As shown below:

public class MyThread extends Thread {

    @Override
    public void run() {
        // 运行多线程的函数代码
    }
}

Create a MyThread object and call the start() method to start a new thread:

MyThread thread = new MyThread();
thread.start();
  1. Implement the Runnable interface

Implementing the Runnable interface is also a way to implement multi-threading. It needs to implement the run() method, but needs to pass a Runnable interface instance to the constructor of the Thread class. As shown below:

public class MyRunnable implements Runnable {

    @Override
    public void run() {
        // 运行多线程函数代码
    }
}

Create and start the thread of MyRunnable:

MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();

The Thread class in Java provides some other methods and properties for monitoring and controlling the status and behavior of the thread, For example, methods such as join(), yield(), sleep(), setPriority() and isAlive().

Multi-threaded synchronization

In multi-threaded programming, multiple threads may access the same resource. At this time, it is necessary to ensure thread synchronization and mutual exclusion to prevent multiple threads from modifying the same resource at the same time, causing data confusion or errors. Java provides a variety of synchronization methods:

  1. Synchronized code block

With the synchronized keyword, a method or code block can be marked as synchronized so that only one entry The block's threads can execute the code within it. As shown below:

public class SynchronizedThread {
    // 定义一个计数器
    private int count = 0;

    // 定义同步的方法
    public synchronized void addCount() {
        count++;
        System.out.println("count = " + count);
    }

    // 定义一个线程类来调用 addCount() 方法
    private static class MyThread extends Thread {
        private SynchronizedThread synchronizedThread;

        public MyThread(SynchronizedThread synchronizedThread) {
            this.synchronizedThread = synchronizedThread;
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                synchronizedThread.addCount();
            }
        }
    }

    public static void main(String[] args) {
        SynchronizedThread synchronizedThread = new SynchronizedThread();
        MyThread thread1 = new MyThread(synchronizedThread);
        MyThread thread2 = new MyThread(synchronizedThread);
        thread1.start();
        thread2.start();
    }
}
  1. Synchronized methods

After marking a method as synchronized, the method will be synchronized and only one thread can enter it. For example:

public synchronized void addCount() {
    count++;
    System.out.println("count = " + count);
}
  1. Lock class

Lock is another synchronization mechanism in Java. It provides more flexible thread synchronization, making it easier to switch between multiple locks. Lock implements the java.util.concurrent.locks.Lock interface and provides the following methods:

  • lock(): Try to obtain the lock. If the lock is already occupied, the thread will Wait until the lock is obtained.
  • unlock(): Release the lock.
  • tryLock(): Try to obtain the lock. If the lock is already occupied, it will return false immediately.
  • newCondition(): Returns the Condition instance related to this lock. Before calling the await() method of Condition, the thread must obtain the object monitor lock associated with the lock.

For example:

Lock lock = new ReentrantLock();

public void addCount() {
    lock.lock();
    try {
        count++;
        System.out.println("count = " + count);
    } finally {
        lock.unlock();
    }
}

Java thread pool

The thread pool in Java is a mechanism for managing and reusing threads. The thread pool can better utilize the CPU performance, reduce the creation and destruction of threads, and improve the response speed of the program. In Java, thread pools can be created through the ThreadPoolExecutor class. You can specify parameters such as the size of the thread pool and the length of the queue, and you can also perform a variety of tasks.

For example:

ExecutorService threadPool = Executors.newFixedThreadPool(10);
threadPool.execute(new Runnable() {
    @Override
    public void run() {
        // 执行任务
    }
});

Summary

Multi-threaded programming in Java is an important means to improve program concurrency and efficiency. In addition to introducing the two ways to create multi-threads in Java (inheriting the Thread class and implementing the Runnable interface), it also introduces various synchronization methods and Java thread pools. Understanding the basic concepts and implementation of multi-threaded programming is crucial to developing efficient, highly concurrency programs.

The above is the detailed content of Multithreaded Programming in Java. 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