admin 管理员组文章数量: 1086019
2024年3月13日发(作者:blastp)
java多线程编程练习题
Java多线程编程练习题
Java是一种广泛应用于开发各种应用程序的编程语言,而多线程编程是Java中
一个非常重要的概念。多线程编程可以提高程序的并发性和效率,充分利用计
算机的多核处理能力。在本文中,我们将介绍一些Java多线程编程的练习题,
帮助读者更好地理解和掌握这一概念。
练习题一:多线程计算累加和
编写一个Java程序,使用多线程计算从1到100的累加和。要求使用两个线程
分别计算1到50和51到100的累加和,然后将结果相加得到最终结果。在计
算过程中,每个线程需要输出自己所计算的部分的累加和,并在计算完成后输
出最终结果。
解答:
```java
public class SumCalculator implements Runnable {
private int start;
private int end;
private int sum;
public SumCalculator(int start, int end) {
= start;
= end;
= 0;
}
public int getSum() {
return sum;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
}
n("Thread " + tThread().getId() + " calculated
sum: " + sum);
}
public static void main(String[] args) throws InterruptedException {
SumCalculator calculator1 = new SumCalculator(1, 50);
SumCalculator calculator2 = new SumCalculator(51, 100);
Thread thread1 = new Thread(calculator1);
Thread thread2 = new Thread(calculator2);
();
();
();
();
int totalSum = () + ();
n("Total sum: " + totalSum);
}
}
```
练习题二:生产者-消费者模型
编写一个Java程序,模拟生产者-消费者模型。假设有一个共享的数据缓冲区,
生产者线程将随机生成一些数据并放入缓冲区,消费者线程将从缓冲区中取出
数据并进行处理。要求生产者和消费者之间需要进行同步,即生产者在缓冲区
已满时需要等待,消费者在缓冲区为空时需要等待。
解答:
```java
import List;
public class ProducerConsumer {
private LinkedList
private int maxSize;
public ProducerConsumer(int maxSize) {
= new LinkedList<>();
e = maxSize;
}
public void produce() throws InterruptedException {
while (true) {
synchronized (this) {
while (() == maxSize) {
wait();
}
int data = (int) (() * 100);
(data);
n("Produced: " + data);
notify();
(1000);
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (this) {
while (y()) {
wait();
}
int data = First();
n("Consumed: " + data);
notify();
(1000);
}
}
版权声明:本文标题:java多线程编程练习题 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1710274845a565601.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论