JAVA 线程安全案例

发布时间 2023-06-16 21:52:41作者: ayiZzzz

# 线程安全案例

## 使用原子类来实现资源的安全保护

```java

public class AtomicSafeExample {

static CountDownLatch countDownLatch = new CountDownLatch(2);



public static void main(String[] args) throws InterruptedException {

Thread thread = new Thread(Performance.INSTANCE , "thread-1");
Thread thread2 = new Thread(Performance.INSTANCE , "thread-2");

// 模拟耗时
Thread.sleep(200);

thread.start();
thread2.start();

// 方式一
// try {
// // 使用 join 进行 thread 和 thread2 的阻塞操作
// thread.join();
// thread2.join();
// }catch (InterruptedException e) {
// }

// 方式二 使用 CountDownLatch

try {
countDownLatch.await();
}catch (InterruptedException e) {

}

System.out.println(Performance.INSTANCE.nums);

}

static enum Performance implements Runnable {

INSTANCE;
AtomicInteger nums = new AtomicInteger(0);

@Override
public void run() {
for (int i = 0 ; i < 100 ; i ++ ) {
nums.incrementAndGet();
}
countDownLatch.countDown();
}
}
}

```

1、Java中的原子类可以使用CAS(Compare And Swap)算法来实现线程安全

2、使用原子类可以简化多线程编程,提高程序的性能和可维护性。如果需要进行线程安全的计数操作、状态标记等,可以考虑使用Java中的原子类。

## ReentrantLock 实现线程安全

```java

public class ReentrantLockSafeExample {

static int nums = 0;

public static void main(String[] args) {
Thread thread = new Thread(Performance.INSTANCE , "thread-1");
Thread thread2 = new Thread(Performance.INSTANCE , "thread-2");

thread.start();
thread2.start();

try {
thread.join();
thread2.join();
}catch (InterruptedException e) {

}

System.out.println(nums);

}

enum Performance implements Runnable {
INSTANCE;

static ReentrantLock lock = new ReentrantLock();

@Override
public void run() {
lock.lock();
try {
for (int i = 0 ; i < 200 ; i ++) {
nums ++ ;
}
}finally {
lock.unlock();
}

}
}

}

```

1、ReentrantLock是Java中的一个可重入锁,它可以用于实现线程间的互斥和同步。

2、使用 ReentrantLock 的基本范式

```java

public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}

```

1、ReentrantLock需要手动释放锁,因此一定要在finally块中调用unlock方法,以确保锁能够被正确释放。

2、使用ReentrantLock可以避免死锁和饥饿等多线程问题,同时提供了更高的灵活性和可扩展性,是Java多线程编程中常用的工具之一。

---

## 使用 synchronized 实现线程安全

```java

public class Counter { private int count; // 使用synchronized实现线程同步 public synchronized void increment() { count++; } public int getCount() { return count; } } public class MyThread extends Thread { private Counter counter; public MyThread(Counter counter) { this.counter = counter; } @Override public void run() { for (int i = 0; i < 10000; i++) { counter.increment(); } } } public class Main { public static void main(String[] args) throws InterruptedException { Counter counter = new Counter(); MyThread thread1 = new MyThread(counter); MyThread thread2 = new MyThread(counter); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println(counter.getCount()); // 输出20000 } }

```

1、synchronized 是 Java 中的关键字,可以用于实现线程间的同步和互斥。使用 synchronized 可以保证在多线程环境下的线程安全性,避免了数据竞争和不一致的问题。

2、synchronized 是一种重量级锁,会对性能产生一定的影响。在使用 synchronized 时,应尽可能减少同步的范围和时间,避免出现死锁和饥饿等多线程问题。