簡體   English   中英

Java-試圖了解線程和新的Thread(this).start();

[英]Java - Trying to understand Threading and new Thread(this).start();

我是Thread的新手。 我試圖了解如何通過制作一個簡單的程序來應用線程的用法。 它似乎不起作用。 該程序只要求兩個輸入,並在將值分配給這兩個變量后立即終止。 此外,如果threadNum變量大於1 ,它會拋出NullPointerException請您說明執行此操作的正確方法嗎? 另外,我對於使用new Thread(this).start();構造和啟動線程感到困惑new Thread(this).start();

package helloworld;

import java.util.Scanner;


public class HelloWorld implements Runnable {

private int threadNum;
private int taskNum;
private int loopNum;

public HelloWorld(int threadNum, int taskNum){
    this.taskNum = taskNum;
    this.threadNum = threadNum;

    int loop = taskNum / threadNum;
    this.loopNum = loop;
}

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("Task Num = ");
    int taskNum = sc.nextInt();
    System.out.print("Thread Num = ");
    int threadNum = sc.nextInt();

    HelloWorld hello = new HelloWorld(threadNum, taskNum);
    hello.activate();

}


public void activate(){
    Thread[] a = new Thread[this.threadNum];
    int count = 0;

    for(Thread x : a){
        x = new Thread(this);
    }

    for(int i = 0; i < a.length - 1 ; i++){

        while(count < loopNum){
            a[i].start();
            count++;
        }
        count = 0;

        while(count < taskNum - ((threadNum - 1) * loopNum)){
            a[a.length - 1].start();
            count ++;
        }
    }
}

@Override
public void run() {

    System.out.println("Processing....");
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    System.out.println("Done !!");
}

}

HelloWorld implements Runnable意味着new Thread(this)Runnable傳遞給Thread的構造函數。 你實際上並沒有填充a在當前的代碼。 你可以那樣做

Thread[] a = new Thread[this.threadNum];
for(int i = 0; i < this.threadNum; i++){
    a[i] = new Thread(this);
}
// Now `a` is filled with threads.
int count = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM