并发编程:Java线程安全和同步方法实例
Java中的并发编程主要涉及到线程安全和同步机制。以下是一些实例来解释这些概念:
线程安全:
// 不安全的例子,多个线程同时读写count可能导致数据不一致
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int decrement() {
if (count > 0) {
count--;
return count;
} else {
throw new RuntimeException("Can't decrement from zero!");
}
}
public synchronized int getCount() {
return count;
}
}
同步方法:
// 使用synchronized关键字来确保同一时间只有一个线程能访问一个临界区(如方法)
public class LockExample {
private Object lock = new Object();
public void criticalSection() {
synchronized (lock) { // 获取锁
System.out.println("criticalSection is executing...");
try {
// 执行临界区操作
Thread.sleep(2000); // 模拟耗时操作
} finally {
lock.notifyAll(); // 通知所有等待锁的线程,让他们继续执行
System.out.println("criticalSection has finished.");
}
}
}
public static void main(String[] args) {
LockExample example = new LockExample();
Thread thread1 = new Thread(() -> {
example.criticalSection();
}));
Thread thread2 = new Thread(() -> {
example.criticalSection();
}));
thread1.start(); // 启动线程1
thread2.start(); // 同理启动线程2
try {
// 等待所有线程执行完毕
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread is finishing.");
}
}
以上代码中,
Counter
类使用synchronized
关键字确保同一时间只有一个线程能访问其方法。这样可以避免数据不一致的情况。
还没有评论,来说两句吧...