// 示例:使用synchronized关键字实现线程安全
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
// 示例:死锁场景
public class DeadlockExample {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
synchronized (lock2) {
// 业务逻辑
}
}
}
public void method2() {
synchronized (lock2) {
synchronized (lock1) {
// 业务逻辑
}
}
}
}
// 示例:使用wait/notify实现生产者-消费者模型
public class ProducerConsumer {
private final List<Integer> buffer = new ArrayList<>();
private final int CAPACITY = 5;
public void produce() throws InterruptedException {
synchronized (this) {
while (buffer.size() == CAPACITY) {
wait();
}
buffer.add(1);
notify();
}
}
public void consume() throws InterruptedException {
synchronized (this) {
while (buffer.isEmpty()) {
wait();
}
buffer.remove(0);
notify();
}
}
}
// 示例:使用线程池提升性能
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
executor.submit(() -> {
// 任务逻辑
});
}
executor.shutdown();
// 示例:使用CountDownLatch实现线程同步
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
// 任务逻辑
latch.countDown();
}).start();
}
latch.await();
// 示例:使用不可变对象避免线程安全问题
public final class ImmutableValue {
private final int value;
public ImmutableValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
// 示例:使用CompletableFuture实现异步编程
CompletableFuture.supplyAsync(() -> {
// 异步任务逻辑
return "Result";
}).thenAccept(result -> {
// 处理结果
});
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有