2017-10-29 3 views
0

変数Nがクラスのcostructorで更新されている場合、どのようにboolean(選択)とint(数値)の配列を更新できますか?変数の1つが更新されている場合、どのように配列を更新できますか?

public class Lamport_Algorithm implements Runnable { 
private static int N = 0; 

private static boolean choosing[] = new boolean[N]; 
private static int number[] = new int[N]; 
private final int idProcess; 

public Lamport_Algorithm(int idProcess) { 
    this.idProcess = idProcess; 

    if (N == 0) { 
     N = 1; 
    } else { 
     N += 1; 
    } 
} 

public void run() { 
    System.out.println("Hello" + "[" + idProcess + "]" + " There are: " + N + " Thread "); 
    for (int i = 0; i < N; i++) { 
     System.out.println(choosing[i]); 
    } 
} } 

これがメインです:

public class MainTest { 
    public static void main(String[] args){ 

     Lamport_Algorithm a = new Lamport_Algorithm(1);   
     Thread T1 = new Thread (a);   
     T1.start();  
    } 
} 
+1

これは並列配列を使用しない主な理由です。 int型とboolean型を保持する型の参照配列を使用し、情報の重複を避けます。 –

+2

つまり、フィールドにstaticを使用しないでください。そしてJavaの命名規則について読んで、_ charの使用をやめてください。 – GhostCat

+0

また、N + = 1を行うことができます。if/elseの必要はありません。結局のところ、ゼロプラス1は1つです。 –

答えて

0

あなたは以下のようなコンストラクタの内部で両方の配列を初期化することができます。

コードの完全版です。

class Lamport_Algorithm implements Runnable { 
private static int N = 0; 

private static boolean choosing[]; 
private static int number[]; 
private final int idProcess; 

public Lamport_Algorithm(int idProcess) { 
    this.idProcess = idProcess; 

    if (N == 0) { 
     N = 1; 
    } else { 
     N += 1; 
    } 

    choosing = new boolean[N]; 
    number = new int[N]; 
} 

public void run() { 
    System.out.println("Hello" + "[" + idProcess + "]" + " There are: " + N + " Thread "); 
    for (int i = 0; i < N; i++) { 
     System.out.println(choosing[i]); 
    } 
} 
} 

class MainTest { 
public static void main(String[] args){ 

    Lamport_Algorithm a = new Lamport_Algorithm(1); 
    Thread T1 = new Thread (a); 
    T1.start(); 
} 
} 
関連する問題