大家好,我是程序员影子
一名致力于帮助更多朋友快速入门编程的程序猿
今天来聊一聊关于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+编程玩法 的相关资料和源码请移步至公众号:程序员影子