Home >Java >javaTutorial >Java multi-threaded programming: thread creation, synchronization and communication

Java multi-threaded programming: thread creation, synchronization and communication

WBOY
WBOYOriginal
2023-05-11 19:51:191623browse

Java multi-threaded programming: thread creation, synchronization and communication

As an object-oriented programming language, Java supports multi-threaded programming and can handle complex multi-task concurrency issues. By decomposing a program into multiple execution threads to execute tasks concurrently, Java's multi-threaded programming can significantly improve the performance of the program.

In Java, a thread is a lightweight execution path that shares memory and other resources with other threads. Each thread performs its own tasks independently, but threads can coordinate and share resources through synchronization and communication.

Creation of threads
There are two ways to create threads in Java: inheriting the Thread class and implementing the Runnable interface.

Inherit the Thread class method:

public class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread is running.");
    }
}

Implement the Runnable interface method:

public class MyRunnable implements Runnable{
    public void run(){
        System.out.println("MyRunnable is running.");
    }
}

The thread startup method is as follows:

// 继承Thread类方式
Thread thread1 = new MyThread();
thread1.start();

// 实现Runnable接口方式
Thread thread2 = new Thread(new MyRunnable());
thread2.start();

Thread synchronization
In Java In multi-threaded programming, since the execution order between threads is unpredictable, if multiple threads access shared resources at the same time, data race problems may occur, resulting in incorrect program results.

In order to ensure correct coordination and data sharing between threads, synchronization mechanisms and object locks are provided in Java. The synchronization mechanism is implemented through the synchronized keyword, and the lock mechanism is implemented through the lock object in Java.

The following is how to use the synchronized keyword:

public class MyCounter {
    private int count;

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

In the above code, the increment() method is a thread-safe method, that is, only one thread can access it at the same time this method.

The following is how to use the lock object:

public class MyCounter {
    private int count;
    private final Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}

In the above code, the increment() method is also a thread-safe method. In order to ensure thread safety, it needs to be passed# first ##lock()The method obtains the object lock, and then releases the object lock after completing the operation.

Thread communication

Thread safety can be ensured through the thread synchronization mechanism, but in some cases coordination and information exchange between threads are required, in which case a thread communication mechanism is required. The thread communication mechanism includes three methods: wait(), notify() and notifyAll().

The wait() method makes the current thread wait and sets the thread's status to the waiting state until another thread uses the notify() method to notify or the wait() time times out. The

notify() method wakes up a thread in the waiting state. If there are multiple threads in the waiting state, only one of the threads can be randomly selected to wake up.

The notifyAll() method wakes up all threads in the waiting state, so that multiple threads in the waiting state can run at the same time.

The following is an example of thread communication:

public class MyQueue {
    private Queue<String> queue = new LinkedList<>();

    public synchronized void put(String value) {
        queue.add(value);
        notify();
    }

    public synchronized String get() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();
        }
        return queue.remove();
    }
}

In the above code, the

put() method adds elements to the queue and uses notify()# The ## method notifies the waiting thread; the get() method waits for elements in the queue, and uses the notify() method to notify the waiting thread when the element is available. Conclusion

Multi-threaded programming in Java is a complex task that requires careful design and implementation to ensure the correctness and performance of the program. Understanding the creation, synchronization and communication mechanisms of threads can help you master the core points of multi-threaded programming in Java, thereby improving the quality and performance of your program.

The above is the detailed content of Java multi-threaded programming: thread creation, synchronization and communication. 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