0

スレッドを待機させる方法を教えてください。たとえば、次の場合に待機し、次の場合i == 0に再度実行しますi == 1

public class Main {

    public Main() { 
    }

    public void method() {

            Thread thread = new Thread(new Task());
            // I want to make wait it when I want
            // for example wait if i == 0 and go again when i = 1
    }

    public static void main(String[] args) {
            new Main();
    }
}
4

4 に答える 4

3

これはCountDownLatchに適しています。

    public static void main( String[] args ) throws Exception {
    final CountDownLatch latch = new CountDownLatch( 1 );
    System.out.println( "Starting main thread" );
    new Thread( new Runnable() {
        public void run() {
            System.out.println( "Starting second thread" );
            System.out.println( "Waiting in second thread" );
            try {
                latch.await();
            } catch ( InterruptedException e ) {
                e.printStackTrace();
            }
            System.out.println( "Stopping second thread" );
        }
    } ).start();

    Thread.sleep( 5000 );
    System.out.println( "Countdown in main thread" );
    latch.countDown();

    Thread.sleep( 1000 );
    System.out.println( "Stopping main thread" );
}
于 2012-06-03T10:34:55.863 に答える
2

セマフォでこれを行うことができるかもしれません

于 2012-06-03T09:38:37.483 に答える
1

このようなフラグを使用することは必ずしも最善のアプローチではありませんが、特定の質問に答えるために:intを作成することができますvolatile。そのまま実行できる簡単な例を以下に示します。これが機能するために重要な事実iです。volatile

出力は次のとおりです(スレッドのインターリーブにより、実行ごとに異なる可能性があります)。

i=1
I'm doing something
I'm doing something
i=0
I'm waiting
I'm waiting
i=1
I'm doing something
I'm doing something
I'm doing something
i=0
I'm waiting
I'm waiting
interrupting
I was interrupted: bye bye

public class TestThread {

    private static volatile int i = 0;

    public static void main(String[] args) throws InterruptedException {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                try {
                    while (true) {
                        while (i == 1) {
                            System.out.println("I'm doing something");
                            Thread.sleep(5);
                        }

                        while (i == 0) {
                            System.out.println("I'm waiting");
                            Thread.sleep(5);
                        }

                    }
                } catch (InterruptedException ex) {
                    System.out.println("I was interrupted: bye bye");
                    return;
                }
            }
        };

        Thread t = new Thread(r);
        t.start();

        i = 1;
        System.out.println("i=1");
        Thread.sleep(10);
        i = 0;
        System.out.println("i=0");
        Thread.sleep(10);
        i = 1;
        System.out.println("i=1");

        Thread.sleep(10);
        i = 0;
        System.out.println("i=0");
        Thread.sleep(10);
        t.interrupt();
        System.out.println("interrupting");
    }
}
于 2012-06-03T10:15:17.547 に答える
1

アクティブな待機を回避するにはwait()、andnotify()またはnotifyAll()メソッドを使用してみてください。Wait()は、誰かがwait ()と同じオブジェクトでnotify( )またはnotifyAll()を呼び出すまで、スレッドを停止させることができます。条件の 1 つは、スレッドがwait()notify()またはnotifyAll()を呼び出すオブジェクトのモニターを所有している必要があることです。

ここに例があります

import java.util.concurrent.TimeUnit;

public class StartPauseDemo extends Thread {
    volatile int i = 1;

    public void pause() {
        i = 0;
    }

    public synchronized void unPause() {
        i = 1;
        notify();// wake up thread
    }

    @Override
    public void run() {
        while (i==1) {
            // logic of method for example printing time every 200 miliseconds
            System.out.println(System.currentTimeMillis());
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (i==0) {
                synchronized (this) {// thread must possess monitor of object on
                                        // which will be called wait() method,
                                        // in our case current thread object
                    try {
                        wait();// wait until someone calls notify() or notifyAll
                                // on this thred object
                                // (in our case it is done in unPause() method)
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // test - pausing and unpausing every 1 sec
    public static void main(String[] args) throws InterruptedException {
        StartPauseDemo sp = new StartPauseDemo();
        sp.start();// start thread
        while (true) {
            System.out.println("pausing");
            sp.pause();
            TimeUnit.SECONDS.sleep(1);

            System.out.println("unpausing");
            sp.unPause();
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

出力:

pausing
unpausing
1338726153307
1338726153507
1338726153709
1338726153909
1338726154109
pausing
unpausing
1338726155307
1338726155507
... and so on
于 2012-06-03T12:23:29.137 に答える