多线程同步:Java中的互斥锁与条件变量实例
在Java中,多线程同步主要通过两种机制实现:互斥锁和条件变量。
- 互斥锁(Mutex)
互斥锁是一种独占资源的工具。当一个线程获得一个互斥锁后,其他线程必须等待该锁被释放才能获取。
实例:
public class MutexExample {
private final Object lock = new Object();
public void thread1() {
synchronized (lock) {
System.out.println("Thread 1: Acquiring lock...");
try {
Thread.sleep(2000); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 1: Lock released, waiting...");
}
}
public void thread2() {
synchronized (lock) {
System.out.println("Thread 2: Acquiring lock...");
try {
Thread.sleep(500); // Simulate shorter work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread 2: Lock released, thread continues...");
}
}
public static void main(String[] args) {
MutexExample example = new MutexExample();
Thread thread1 = new Thread(example::thread1));
Thread thread2 = new Thread(example::thread2));
thread1.start(); // Start the first thread
thread2.start(); // Start the second thread
try {
thread1.join(); // Wait for thread 1 to finish
thread2.join(); // Wait for thread 2 to finish
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Both threads finished.");
}
}
在上述代码中,MutexExample
类包含一个互斥锁lock
。两个线程thread1
和thread2
分别对锁进行操作。
当一个线程获得了锁后,其他线程必须等待锁被释放才能获得。这样就实现了多线程的同步控制。
还没有评论,来说两句吧...