【发布时间】:2014-10-11 03:11:34
【问题描述】:
我正在尝试为 Java 中的多线程问题编写我的解决方案:
创建三个单独的线程来计算平均值、最小值 以及传递给程序的一系列数字中的最大值。这 值将全局存储在程序中。这三个线程将 将这三个值分别返回到主程序中 输出给用户。
我是 Java 新手,所以我有一个关于这个程序的方法的基本问题:如何创建三个单独的线程来执行 三个不同的功能强>?在阅读多线程时,我遇到了几个示例,其中创建了三个(或更多)线程,每个线程将执行一个函数:counting down a loop。因此只需要一次调用public void run() 就可以很容易地创建一个实现 Runnable 的类的三个实例来执行此操作,例如:
// Create multiple threads.
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class MultiThreadDemo {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
我不确定如何创建执行单独功能的线程:计算双精度、最小值和最大值。到目前为止,我已经创建了一个线程来计算平均值并将其返回给主程序。这是我的代码 [直到现在]:
package assignment2;
class Q2Thread implements Runnable {
String name;
Thread t;
private int average;
int sum=0;
Q2Thread(String name)
{
this.name=name;
t=new Thread(this, name);
//System.out.println("This thr");
t.start();
}
public void run()
{
try
{
for(int i=0;i<Q7Main.arr.length;i++)
sum+=Q7Main.arr[i];
average=sum/Q7Main.arr.length;
}
//catch(InterruptedException e)
finally
{
System.out.println("Calcuated average.");
}
System.out.println("Child Thread exiting.");
}
public int getAverage()
{
return average;
}
}
package assignment2;
import java.util.*;
public class Q7Main {
public static int[] arr=new int[5];
static Scanner in=new Scanner(System.in);
private static int finalAverage;
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Please enter the numbers: " );
for(int i=0;i<arr.length; i++)
arr[i]=in.nextInt();
System.out.println("You entered the numbers: ");
for(int x: arr)
{
System.out.print(x+ " ");
}
System.out.println();
Q2Thread obj=new Q2Thread("Average");
try
{
obj.t.join();
}
catch(InterruptedException e)
{
System.out.println("Interrupted.");
}
finalAverage=obj.getAverage();
System.out.println("The average of the numbers is: "+ finalAverage);
}
}
我现在有两个问题:
- 谁能告诉我创建另外两个线程来计算最小值和最大值的方法?
- 我的代码(到目前为止)中是否有任何我应该注意的 OOP 缺陷?
【问题讨论】:
标签: java multithreading