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 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().
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(); } }
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
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!