2012-03-22 5 views
0

私はプログラムの詳細を記述しています: 1.ユーザーは配列に値を入力し、 0を各インデックスに挿入する必要があります。 2.スレッドを使用すると、最初にスレッドが呼び出され、ユーザーが入力した値が減少し(2)、1秒間スリープ状態になります。 スリープコールでは、2番目のスレッドは1をインクリメントしてから2秒間スリープし、再び1番目のスレッドはインクリメントされた値でデクリメントし、減少したスレッドの値が0になるまで続きます。 減分の値がゼロに等しいので、自動的に増分を停止する必要があります。Javaで配列を取って、その値をスレッドを使って1回増分して2回増分する必要があります

いずれかが私の質問を理解している場合、私は、コードを持っている今、あなたはnewThreadのインスタンスを作成し、すべてのコメントが...あなたの主な方法で

 //Through Implementing Runnable Interface 

     //Create a second thread 

     //import java.util.Scanner; 




class NewThread extends Thread implements Runnable { 
Thread t; 
NewThread(){ 
//Create a new, second thread 

t = new Thread(this, "Demo AASSINGMENT"); 
//System.out.println("Child Thread: "+ t); 
t.start();//Start the thread 

} 

//This is the entry point for the second thread. 


public void run(){ 

    try{ 
for(int i = 10; i>0; --i){ 

System.out.println("Decrement: " +i); 
//i--; 
//System.out.println("Child Thread 2nd dec: " + i); 
Thread.sleep(1000); 
} 
    } 


catch(InterruptedException e){ 
System.out.println("Decrement INterrupted"); 
} 

System.out.println("Oops!! -- Decreasing Value is less than or equal to zero"); 
}//run 

}//class 



class ThreadDemo { 


public static void main(String args[]){ 
new NewThread();//create a new thread 
int[] arr; int dj; 

// Scanner input = new Scanner(System.in); 
    // System.out.print("Enter Your Desired Value : "); 
    //int z = input.nextInt(); 
    try{ 

    //arr = new int[z]; 
    //for(dj =0; dj<array.length;dj++) 
    //{ 
     // array[dj]=0; 
     // System.out.println("0's inserted "+ array[dj]); 
    //} 

       //while(z!=0){ 

    for(int i = 10; i<=14; i++){ 

    System.out.println("Increment: " +i); 
    //if(i>6){ 
    //System.out.println("Main Thread Exiting");} 
    Thread.sleep(2000); 

        }//for 

    }//try 

catch(InterruptedException e){ 
System.out.println("Main Thread Interrupted"); 
} 
System.out.println("Increasing Value has exceeded from 14 so Exiting"); 


    }//main 
    }//class 
+0

インデントあなたのコードを!または誰もそれを読んでみたくないでしょう。 –

+0

私はこれを編集することを諦めています... –

+0

誰も私の問題を解決する方法を教えてもらえますか? –

答えて

2

を理解すべきである...

私を助けてしかし、あなたはそれを始めることはありません。起動しない限り、決して実行されません。

編集通常、あなたのクラスはThreadを拡張する必要はありませんが、以下の説明への前駆体としてより実装情報

を提供します。代わりにRunnableを実装し、Runnableインスタンスを実行する標準Threadインスタンスを作成します。

だから、私は次のようにコードを変更することを示唆している:

class NewRunnable implements Runnable 
{ 
    public void run() 
    { 
     // Do important background stuff here 
    } 
} 

public static void main (String[] args) 
{ 
    Thread thr = new Thread (new NewRunnable()) ; 
    thr.start() ; 

    // Do other important stuff 
} 
+0

Muhammad [コメントを投稿](http://stackoverflow.com/suggested-edits/225538)彼は実際にそれを開始する必要があります。 – Rup

+0

バックグラウンドスレッドを作成して実行する方法に関する情報を含めるように答えを更新しました。 –

関連する問題