【发布时间】:2017-03-24 10:19:00
【问题描述】:
我需要编写两个程序。 1 个顺序(完成)和 1 个并行,我做了一些事情,但我不知道我是否让它并行,我也需要知道:
- If (Thread.State state = Thread.currentThread().getState();) 是显示线程状态的代码
- 如何将不同的线程分配给不同的处理器(4 核)
- 如何显示处理器的状态
- 每个处理器的计算
- 如何生成错误消息(内存一致性错误等)
以下是我的代码:
class Threads implements Runnable {
@Override
public void run() {
Thread t = Thread.currentThread();
Thread.State state = Thread.currentThread().getState();
String Assignment = "calculations in array";
String name = "os.name";
String version = "os.version";
String architecture = "os.arch";
String[] array = new String[1312500];
int size = array.length;
Random r = new Random();
int[] values = new int[1312500];
int sumarray = 0;
int CountD = 0;
for (int i = 0; i < values.length; i++) {
int randomint = r.nextInt(100);
values[i] = randomint;
if ((values[i] % 2 != 0) && (values[i] >= 25 && values[i] <= 75)) {
sumarray += values[i];
CountD++;
}
}
System.out.println(t.getName());
System.out.println("Thread Id " + t.getId());
System.out.println("Thread Priority " + t.getPriority());
System.out.println("status " + state);
System.out.println("OS Name: " + System.getProperty(name));
System.out.println("OS Version: " + System.getProperty(version));
System.out.println("OS Architechture: " + System.getProperty(architecture));
System.out.println(Assignment);
System.out.println("Size of the Array is: " + array.length);
System.out.println("Total number of system cores(processors): " + Runtime.getRuntime().availableProcessors());
System.out.println("Difference of Array and Processors 1312500/4 = "
+ array.length / Runtime.getRuntime().availableProcessors());
System.out.println("The size of array is divisible by the number of processors");
System.out.println("Summary is: " + sumarray);
System.out.println("The Average is: " + (sumarray / CountD));
}
}
主类:
class Concurrent {
public static void main(String[] args) {
Thread t1 = new Thread(new Threads());
t1.start();
Thread t2 = new Thread(new Threads());
t2.start();
Thread t3 = new Thread(new Threads());
t3.start();
Thread t4 = new Thread(new Threads());
t4.start();
}
}
【问题讨论】:
-
您需要在谷歌上搜索有关线程和 Java 的教程并从那里开始。祝你好运。
-
做了很多,但仍然感到困惑,甚至找不到与我的需求相关的任何东西。
-
您好,欢迎来到 Stackoverflow。请阅读tourguide,了解如何以正确的方式提问以及 stackoverflow 的工作原理。
-
寻求帮助是否太过分了,我不会告诉别人为我做我的工作
-
我(也许其他人也是)尝试想象您的问题背后的基本原理,并忍不住建议您学习 Java、线程、操作系统和 CPU 方面的知识
标签: java arrays multithreading parallel-processing cpu-cores