-2

複数のスレッドを並べて実行したい。
例:単純なカウンターメソッドがあり、スレッドはメソッドにアクセスしてカウンター値を出力します。あるスレッドは、開始する前に別のスレッドが停止するのを待つべきではありません。

サンプル出力[多分]:

T1 1
T2 1
T1 2
T1 3
T1 4
T2 2
T1 5

マルチスレッドについての事前のアイデアはなく、ただ学びたいだけです。

4

3 に答える 3

1

あなたは本当に具体的なことを何も聞いていません。2つ以上のスレッド間で共有されている非スレッドセーフカウンターの一般的な例を探しているだけの場合は、次のようになります。

public class Counter extends Thread {
    private static int count = 0;

    private static int increment() {
        return ++count;  //increment the counter and return the new value
    }

    @Override
    public void run() {
        for (int times = 0; times < 1000; times++) {  //perform 1000 increments, then stop
            System.out.println(increment());  //print the counter value
        }
    }

    public static void main(String[] args) throws Exception {
        new Counter().start();   //start the first thread
        new Counter().start();   //start the second thread
        Thread.sleep(10000);     //sleep for a bit
    }
}
于 2012-10-06T13:46:31.593 に答える
1

カウンターが共有されている場合は、次のようなものが必要です。

class ThreadTask implements Runnable {
    private static AtomicInteger counter = new AtomicInteger();
    private int id;

    public ThreadTask(int id) { this.id = id; }

    public void run() {
        int local = 0;
        while((local = counter.incrementAndGet()) < 500) {
            System.out.println("T" + id + " " + local);
        }
    }
}

...

new Thread(new ThreadTask(0)).start();
new Thread(new ThreadTask(1)).start();

それ以外の場合、スレッドごとのカウンターが必要な場合:

class ThreadTask implements Runnable {
    private int counter = 0;
    private int id;

    public ThreadTask(int id) { this.id = id; }

    public void run() {
        while(counter < 500) {
            counter++;
            System.out.println("T" + id + " " + counter);
        }
    }
}

...

new Thread(new ThreadTask(0)).start();
new Thread(new ThreadTask(1)).start();
于 2012-10-06T13:47:30.063 に答える
0

実際の質問はありません...

複数のスレッドを開始して、同期されたprintCounterメソッドにアクセスさせることができると思います。

何かのようなもの

public class MyRunnable implemetns Runnable {
   private SharedObject o
   public MyRunnable(SharedObject o) {
       this.o = o;
   }
   public void run() {
       o.printCounter();  
   }
}

それから始めるためにあなたはただすることができます

new Thread(new MyRunnable()).start();
new Thread(new MyRunnable()).start();

次に、sharedObjectメソッドに、印刷可能な変数を保持するメソッドが必要です。このメソッドは、カウンターもインクリメントできます。

ただし、スレッドスケジューラは、スレッドがいつ実行されるかを保証するものではないことに注意してください。

于 2012-10-06T13:44:49.893 に答える