Java多线程编程

时间:2013-12-08 09:28:09

标签: java

我是Java编程学习者的初学者。我不知道如何更正以下Java程序。请帮助我告诉我如何纠正它。非常感谢。

公共课TMA1Q2 {

public static void main(String[] args) {
    System.out.println("Usage: java TMA1Q2 {number of Threads}");

    // Create tasks
    Runnable taskA = new PrintTwoConcurThreads("Thread A ");
    Runnable taskB = new PrintTwoConcurThreads("            Thread B ");

    // Create threads
    Thread thread1 = new Thread(taskA);
    Thread thread2 = new Thread(taskB);

    // Start threads
    thread1.start();
    thread2.start();
}

}

//实现Runnable的任务

class PrintTwoConcurThreads implements Runnable {

private final String TwoConcurThreads;
private String[] args;

public PrintTwoConcurThreads(String numThreads) {
    TwoConcurThreads = numThreads;
}

// Override the run() method
@Override
public void run() {
    // Print the value input argument times
    int numThreads = Integer.parseInt(args[0]);
    Thread[] myThread;
    myThread = new Thread[numThreads];
    for (int i = 0; i < numThreads; i++) {
        System.out.println(TwoConcurThreads + i);
    }
}
}

1 个答案:

答案 0 :(得分:1)

private String[] args;

args字段从未初始化,因此默认值为null

当您尝试在以下行中访问它时,您会收到NullPointerException

int numThreads = Integer.parseInt(args[0]);

目前尚不清楚你要做什么。至少这会帮助你看出出了什么问题。

此外,我不知道为什么使用以下行,您创建Thread[]但从未使用它。

Thread[] myThread;
myThread = new Thread[numThreads];