java多线程值相加
时间: 2024-10-22 10:12:33 浏览: 34
在Java中,多线程可以用于并行计算,比如两个变量的值相加。你可以创建两个独立的线程分别持有需要相加的数值,然后在线程内部更新这两个数值,最后将结果汇总。下面是一个简单的例子:
public class ThreadSum {
private int a = 0;
private int b = 0;
// 创建一个新的线程来增加a的值
private Thread threadA = new Thread(() -> {
for (int i = 0; i < 5000; i++) {
synchronized (this) {
a += i;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 创建另一个线程来增加b的值
private Thread threadB = new Thread(() -> {
for (int j = 0; j < 5000; j++) {
synchronized (this) {
b += j;
notify();
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
public void startThreads() {
threadA.start();
threadB.start();
}
public int sum() {
return a + b;
}
public static void main(String[] args) {
ThreadSum sumThread = new ThreadSum();
sumThread.startThreads();
System.out.println("Sum after threads complete: " + sumThread.sum());
}
}
在这个例子中,synchronized
关键字用于保证对共享数据a
和b
的操作互斥,避免数据竞争。wait()
和notify()
则是用来协调两个线程的工作。
相关推荐

















