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 buffer;

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);

}

}


本文标签: 消费者 生产者 缓冲区 编程 程序