并发编程:Java线程安全和同步方法实例

原创 迷南。 2024-09-12 06:33 183阅读 0赞

Java中的并发编程主要涉及到线程安全和同步机制。以下是一些实例来解释这些概念:

  1. 线程安全:

    1. // 不安全的例子,多个线程同时读写count可能导致数据不一致
    2. public class Counter {
    3. private int count = 0;
    4. public synchronized void increment() {
    5. count++;
    6. }
    7. public synchronized int decrement() {
    8. if (count > 0) {
    9. count--;
    10. return count;
    11. } else {
    12. throw new RuntimeException("Can't decrement from zero!");
    13. }
    14. }
    15. public synchronized int getCount() {
    16. return count;
    17. }
    18. }
  2. 同步方法:

    1. // 使用synchronized关键字来确保同一时间只有一个线程能访问一个临界区(如方法)
    2. public class LockExample {
    3. private Object lock = new Object();
    4. public void criticalSection() {
    5. synchronized (lock) { // 获取锁
    6. System.out.println("criticalSection is executing...");
    7. try {
    8. // 执行临界区操作
    9. Thread.sleep(2000); // 模拟耗时操作
    10. } finally {
    11. lock.notifyAll(); // 通知所有等待锁的线程,让他们继续执行
    12. System.out.println("criticalSection has finished.");
    13. }
    14. }
    15. }
    16. public static void main(String[] args) {
    17. LockExample example = new LockExample();
    18. Thread thread1 = new Thread(() -> {
    19. example.criticalSection();
    20. }));
    21. Thread thread2 = new Thread(() -> {
    22. example.criticalSection();
    23. }));
    24. thread1.start(); // 启动线程1
    25. thread2.start(); // 同理启动线程2
    26. try {
    27. // 等待所有线程执行完毕
    28. thread1.join();
    29. thread2.join();
    30. } catch (InterruptedException e) {
    31. e.printStackTrace();
    32. }
    33. System.out.println("Main thread is finishing.");
    34. }
    35. }

    以上代码中,Counter类使用synchronized关键字确保同一时间只有一个线程能访问其方法。这样可以避免数据不一致的情况。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,183人围观)

还没有评论,来说两句吧...

相关阅读