0

私は次のように何かをしようとしています -

  1. スレッドが作成されます
  2. 新しいスレッドが作成されると、前のスレッドの変数が更新されますlimit
  3. 進行状況は 3 番目のスレッドで繰り返されます。つまり、このスレッドlimitはスレッド ID1 と ID2 の変数を更新します。

ここにいくつかのサンプルコードがあります

メインクラス

public class TaskImplementer {
    public static int End;
    public static int threadCount = 5;

    public static void main(String[] args) {
    int i=0;

    findEnd();

    while (i < threadCount) {
        if(isPossible()) {      // check for some condition
        createThread aThread = new createThread(i, End);
        aThread.start();
        }
        i++;
        //updateGUI();  //updateGUI - show working Threads
    }
    }

    private static void findEnd() {
    //updates End variable
    }

    private static boolean isPossible() {
    //.....
    //Check for a condition
    return false;

    }
}

createThread クラス

public class createThread extends Thread {
    private static int ID;
    private static int limit;
    private static int startfromSomething;

    public createThread(int ThreadID, int End) {
    ID = ThreadID;
    limit = End;
    }

    private void doSomething() {
    //does work
    }

    @Override
    public void run() {

    while(startfromSomething < limit) {
        doSomething();
    }
    TaskImplementer.i--;
    }

}

変数limitは、正常に作成された各スレッドによって更新される必要があります。可能ですか、何か提案してください。前もって感謝します。

4

3 に答える 3

0

手順で指定したロジックに基づいて、CreateThreadの配列を作成し、idとlimitのパラメーターを設定できます。

public class TaskImplementer {
    static int End;
    static int threadCount = 5;

    public static void main(String[] args) {
        int i = 0;
        CreateThread[] tasks = new CreateThread[threadCount];
        while (i < threadCount) {
            int j = 0;
            while (j <= i) {

                if (tasks[j] != null) {
                    // Set ID and limit
                    tasks[j] = new CreateThread(j, End);
                    tasks[j].start();
                }
                j++;
            }
            i++;
        }
    }
}
于 2012-10-20T17:22:06.987 に答える
0

createThread クラス内にアトミック整数が必要であり、リストを介して使用可能なスレッド (createThread) オブジェクトを保持する必要があると思います。別のスレッドを実行するたびに、それをリストに追加し、同時に制限変数を増減する必要がありますスレッドリストの参照を介して他の実行中のスレッド、つまり、スレッドプールのようなものを実装する必要があります。

于 2012-10-20T10:51:37.350 に答える
0

問題は明らかに、使用してはならない「静的」の使用によるものです! これは次のようになります。

public class CreateThread extends Thread {
   private int ID;
   private int limit;
   private static int startfromSomething; //Don't know about this one. If this value is the same for every thread, "static" is correct. Otherwise remove "static".

   public createThread(int ThreadID, int End) {
      ID = ThreadID;
      limit = End;
   }
}

このクラスのすべてのインスタンスと静的コンテンツ間でフィールドを共有する場合は、「静的」を使用します。

もう 1 つ: Java コードの規則では、クラス名を大文字で始める必要があります。

于 2012-10-20T17:33:33.117 に答える