Java | 线程同步和异步

大家好,我是程序员影子

一名致力于帮助更多朋友快速入门编程的程序猿

今天来聊一聊关于Java中的线程同步和异步

一、线程同步

线程同步是用于控制多个线程访问共享资源的方式,以避免数据不一致的问题。Java提供了synchronized关键字来实现线程同步。
demo:

public class Counter {
    private int count = 0;
    // 使用synchronized关键字同步方法
    public synchronized void increment() {
        count++;
    }
    public synchronized int getCount() {
        return count;
    }
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("计数器的最终值: " + counter.getCount()); // 输出结果应为2000
    }
}

二、线程异步

线程异步是指多个线程的操作相互独立,一个线程的操作不会影响到其他线程的操作。Java中的Future接口和Callable接口通常用于实现异步编程。
demo:

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class AsyncExample {
    public static void main(String[] args) {
        FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int result = 0;
                for (int i = 0; i < 100; i++) {
                    result += i;
                }
                return result;
            }
        });
        Thread computeThread = new Thread(futureTask);
        computeThread.start();
        try {
            // 主线程可以继续执行其他任务
            System.out.println("主线程可以继续执行其他任务...");
            // 获取异步计算结果
            Integer result = futureTask.get();
            System.out.println("异步计算结果: " + result); // 输出结果应为4950
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、使用ReentrantLock进行同步

ReentrantLock是Java中另一种同步机制,相比synchronized,它提供了更灵活的锁定操作,比如尝试锁定、锁定中断等。
demo:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockExample {
    private final Lock lock = new ReentrantLock();
    private int count = 0;
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
    public int getCount() {
        return count;
    }
    public static void main(String[] args) {
        ReentrantLockExample example = new ReentrantLockExample();
        Thread t1 = new Thread(example::increment);
        Thread t2 = new Thread(example::increment);
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("计数器的最终值: " + example.getCount()); // 输出结果应为2
    }
}

以上就是本次分享的所有内容,感兴趣的朋友点个关注呀,感谢大家啦~

更多Java | AI+编程玩法 的相关资料和源码请移步至公众号:程序员影子 

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值