Java | 线程同步和异步

原创程序员影子

程序员影子

gh_8e9334a5139c

一名热爱生活的程序员、深耕AI+编程实践玩法 | 分享:Java知识、AI+编程实践玩法、职场故事 | 目标:帮助更多朋友快速学会AI+编程提高开发效率,踏上AI时代的邮轮,不被淘汰 | 爱好:AI、编程、职场感悟、音乐、读书、运动

大家好,我是程序员影子|全网同名

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

今天来聊一聊关于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 futureTask = new FutureTask(new Callable() {
            @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
    }
}

限 时 特 惠: 本站每日持续更新海量各大内部创业教程,一年会员只需98元,全站资源免费下载 点击查看详情
站 长 微 信: lzxmw777

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注