按要求编写Java语言程序,实现如下功能: 从标准输入stdin中读取两个正整数m和n, 然后开启n个线程,每个线程【依次轮流】输出【一个数字】和【自己的线程编号】到标准输出stdout, 所有线程输出的结果数列a的前m项。 数列a的定义为:a(1)=2347,a(2)=3917,a(k)=[a(k-1)^2 + 9337*a(k-2) + 6047] mod 10000 例如,m=100,n=2的情况,就是两个线程x和y交替输出。线程x输出2347,然后线程y输出3917,然后线程x输出a(3)即9673,然后线程y输出a(4)即9807……直到线程x输出a(99)的值、线程y输出a(100)的值后程序结束。
时间: 2024-02-06 10:08:45 浏览: 96
一个java编写的程序
以下是Java语言程序的实现:
```
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
private static final int[] a = new int[102];
private static final AtomicInteger currentIndex = new AtomicInteger(1);
public static void main(String[] args) {
int m, n;
System.out.print("请输入m和n:");
m = Integer.parseInt(System.console().readLine());
n = Integer.parseInt(System.console().readLine());
a[1] = 2347;
a[2] = 3917;
Thread[] threads = new Thread[n];
for (int i = 0; i < n; i++) {
threads[i] = new Thread(new Worker(i));
threads[i].start();
}
try {
for (Thread thread : threads) {
thread.join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 1; i <= m; i++) {
System.out.print(a[i] + " ");
}
}
private static class Worker implements Runnable {
private final int index;
public Worker(int index) {
this.index = index;
}
@Override
public void run() {
int i = 1;
while (true) {
synchronized (currentIndex) {
if (currentIndex.get() > 100) {
return;
}
if (index == currentIndex.get() % 2) {
System.out.println(a[currentIndex.get()] + " " + index);
currentIndex.incrementAndGet();
i++;
continue;
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static {
for (int i = 3; i <= 100; i++) {
a[i] = (a[i - 1] * a[i - 1] + 9337 * a[i - 2] + 6047) % 10000;
}
}
}
```
该程序通过创建n个线程,并使用AtomicInteger来保证线程间的同步,实现了从标准输入读入m和n,并按照题目要求输出数列a的前m项。程序中使用了synchronized关键字保证线程安全,并且使用了Thread.sleep()方法来减轻CPU负担,提高程序性能。
阅读全文