无法使用java多线程计算元音

时间:2016-06-25 00:56:49

标签: java multithreading cmd

这就是我想要做的事情:

enter image description here

CountVowel.java

package lab2;


/**
 *
 * @author Shyam
 */

public class CountVowel implements Runnable {
    String[] input;
    int vowels = 0;
    char ch;

    public CountVowel(String[] args) {
        input=args;
    }

    public void run() {
        try {
        for (int i = 0; i < input.length; i++) {
                String s = input[i];

                for (int j = 0; j < s.length(); j++) {
                    ch = s.charAt(j);

                    if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o'
                            || ch == 'O' || ch == 'u' || ch == 'U')
                        vowels++;
                }
            }
            System.out.println("Vowels : " + vowels);

        } catch (Exception e) {
        }
    }

}

VowelThread.java

package lab2;


/**
 *
 * @author Shyam
 */

import java.io.IOException;

public class VowelThread  {

    public static void main(String[] args) 
                throws IOException {
        for (String str : args) {
            System.out.println(str);
        }
        Thread t1 = new Thread(new CountVowel(args));
        t1.start();
    }
}

我尝试过不同的方法,如下所示在cmd中输入字符串但是我没有得到满足的要求。

enter image description here

enter image description here

C:\Users\Shyam\Documents\NetBeansProjects\lab2\src>java VowelCounter hello hello see you in
Error: Could not find or load main class VowelCounter


C:\Users\Shyam\Documents\NetBeansProjects\lab2\src>javac -cp . lab2\VowelThread.java hello hello see you in london
error: Class names, 'hello,hello,see,you,in,london', are only accepted if annotation processing is explicitly requested
1 error

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

在运行javac命令之前,请确保在同一目录中有两个源文件。然后运行命令:

javac CountVowel.java VowelThread.java

只有在将两个类编译成.class文件之后,才能运行程序,例如:

java VowelThread arg1 arg2

但是,在多线程实现中也存在一些问题。您应该继续为每个参数生成一个单独的线程,方法是将new Thread部分放在for循环中,因为我相信您在编辑问题之前已经拥有它,但是您应该将该线程传递给参数它产生于,而不是整个参数列表。其次,一旦你完成了这个设置,你需要找到一种让所有线程更新公共计数的方法。

顺便说一句,在担心多线程Java之前,了解有关单线程Java的更多信息可能是明智之举。

答案 1 :(得分:1)

由于您没有为每个提供的参数创建新的Thread,因此您并没有真正做到所期望的事实,实际上您只为所有参数创建了一个Thread

要实现它,您可以使用FutureTask并让您的课程CountVowel实现Callable,而不是这样的:

public class CountVowel implements Callable<Integer> {
    private final String input;

    public CountVowel(String input) {
        this.input = input;
    }

    public Integer call() {
        int vowels = 0;
        // Iterate over all the characters of the input String
        for (int j = 0; j < input.length(); j++) {
            // Lower case the current character as we need to ignore the case
            char ch = Character.toLowerCase(input.charAt(j));
            // Use a switch statement instead of an if as it is easier to read and faster
            switch (ch) {
                case 'a':
                case 'e':
                case 'o':
                case 'i':
                case 'u':
                    vowels++;
                    break;
            }
        }
        // Returns the sub total
        return vowels;
    }
}

主要课程将是这样的:

public class VowelThread {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // Create the list that will contain all the tasks
        List<FutureTask<Integer>> futures = new ArrayList<>();
        for (String str : args) {
            // Create a task for the current String
            FutureTask<Integer> future = new FutureTask<>(new CountVowel(str));
            // Add the task to the list of tasks
            futures.add(future);
            // Provide the task to a new Thread and start it
            new Thread(future).start();
        }
        int total = 0;
        // Iterate over all the tasks
        for (FutureTask<Integer> task : futures) {
            // Wait as long as it is needed to get the result of the current task
            total += task.get();
        }
        // Print the total of vowels found
        System.out.printf("Number of vowels: %d%n", total);
    }
}

关于问题的第二部分,您需要从javac目录启动src命令,否则它无法编译,因为您的类位于包lab2中,因此它应该在您发布lab2命令的目录javac中。

因此,假设您在src,预期的命令如下:

javac lab2\VowelThread.java 
java lab2.VowelThread Hello Hello see you in Italy in Venice

<强>输出:

Number of vowels: 15

答案 2 :(得分:1)

import java.lang.*;

class MyThread extends Thread    
{
String input;
static int vowels;
MyThread(String input)
{
    this.input=input;
}
public void run()
{
    char ch;
    try
    {
        for(int i=0; i<input.length(); i++)
        {
            ch=input.charAt(i);
            if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' || ch == 'I' || ch == 'o'|| ch == 'O' || ch == 'u' || ch == 'U')
                vowels++;
        }
    }
    catch(Exception ie)
    {
    }
}
}

class Demo
{
public static void main(String args[])
{
    for(int i=0; i<args.length; i++)
    {
        new MyThread(args[i]).start();
    }
    System.out.println("Number of Vowels:\t"+MyThread.vowels);
}
}