-1
   import java.util.Scanner;
   import java.lang.Thread;

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


   for(int i = 0; i<=10;i++){
      System.out.println(i);
      thread.sleep(1000);
   }
  }
 }

ご覧のとおり、プログラムに 10 までカウントさせたいのですが、動作させるには何を入力すればよいでしょうか?

おそらく、Eclipse では「スレッドを解決できません」というエラーであると言うべきでした。

4

7 に答える 7

1

Thread クラスは例外をスローする可能性があるため、Thread.sleep(1000) を try-catch ブロックに入れます。

public static void main (String[] args) throws InterruptedException
    {
        for(int i = 0; i<=10;i++)
        {
            System.out.println(i);
            Thread.sleep(1000);
        }
    }
于 2013-06-26T12:21:56.013 に答える
1

試す

try {
    for (int i=1;i<=10;i++) {
      System.out.println(i);
      Thread.sleep(1000);
    }
 } catch(InterruptedException e) {
        e.printStackTrace();
 }
于 2013-06-26T12:20:01.803 に答える
0

あなたはこのようにそれを行います

try {
  for(int i = 0; i < 10; i++) {
      Thread.sleep(1000);
      System.out.println("Counter at " + i + " seconds");
  }
} catch(InterruptedException e) {
  // Thread got interrupted
}
于 2013-06-26T12:22:43.887 に答える
0

javac OrigClass.java

java OrigClass

それがあなたが求めているものであれば、それをコンパイルして実行します。

于 2013-06-26T12:20:52.227 に答える
0

Thread.sleep() を自分で処理したくない場合、および回避する正当な理由がある場合は、Timer および TimerTask を使用できます。以下の例

import java.util.Timer;
import java.util.TimerTask;

public class TimerSample {

    public static void main(String[] args) {
        TimerTask task = new TimerTask() {

            int count = 0;

            @Override
            public void run() {
                // Whenever task is run, we will print the count
                System.out.println(count);
                count++;

                // If count reaches 10, we will cancel the task                    
                if (count >= 10) {
                    cancel();
                }
            }
        };

        //Schedule a timer that executes above task every 1 second
        Timer t = new Timer();
        t.schedule(task, 0, 1000);
        return;
    }
}

より興味深い使用例がここで説明されています: http://www.ibm.com/developerworks/java/library/j-schedule/index.html

于 2013-06-26T12:56:04.377 に答える
0

大文字の「t」が必要です。すなわち書くThread.Sleep();。ただしjava.util.concurrent.TimeUnit.SECONDS.sleep(1);、より明確であるため、使用することをお勧めします。

そして、処理する必要があるjava.lang.InterruptedExceptionか、コードがコンパイルされません。

これをまとめて書く

try {
    for (int i = 0; i < 10; ++i){
        /* Print the counter then sleep for a bit
         * Perhaps this is the wrong way round?
         */
        System.out.println(i);
        java.util.concurrent.TimeUnit.SECONDS.sleep(1);
    }
} catch (final java.lang.InterruptedException e){
   // ToDo - Handle the interruption.        
}
于 2013-06-26T12:26:01.033 に答える