理解和解决Java多线程同步问题的示例
在Java中,多线程同步主要是通过锁(Lock)机制来实现的。常用的锁包括 synchronized 关键字、ReentrantLock 等。
以下是一个使用synchronized关键字和打印线程名称来同步两个线程的简单示例:
public class SynchronizedExample {
private int count = 0;
public void increment() {
synchronized (this) { // 同步块,锁定当前对象
count++;
System.out.println("Thread " + Thread.currentThread().getName() + " incremented count to " + count);
}
}
public static void main(String[] args) {
SynchronizedExample example = new SynchronizedExample();
Thread thread1 = new Thread(() -> example.increment()));
Thread thread2 = new Thread(() -> example.increment()));
thread1.start(); // 启动线程1
thread2.start(); // 启动线程2
// 等待线程结束
thread1.join();
thread2.join();
System.out.println("Final count: " + example.count)); // 验证最终计数是否正确
}
}
在上述示例中,两个线程(thread1
和 thread2
)同时调用 increment()
方法。由于同步块的存在,任何时刻只有一个线程可以执行同步代码,从而保证了正确的计数结果。
还没有评论,来说两句吧...