Yoda
Yoda

Reputation: 18068

Making Thread just wait

Please show me how to make thread wait. for example wait if i == 0 and go again when 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();
    }
}

Upvotes: 0

Views: 187

Answers (4)

Pshemo
Pshemo

Reputation: 124225

To avoid active waiting try use wait() and notify() or notifyAll() methods. Wait() can make thread stop until someone call notify() or notifyAll() on same object as wait(). One of condition is that thread must be in possession of monitor of object on which will be invoking wait(), notify() or notifyAll().

Here is an example

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);
        }
    }
}

Output:

pausing
unpausing
1338726153307
1338726153507
1338726153709
1338726153909
1338726154109
pausing
unpausing
1338726155307
1338726155507
... and so on

Upvotes: 1

Oded Peer
Oded Peer

Reputation: 2427

This is suitable for a 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" );
}

Upvotes: 3

assylias
assylias

Reputation: 328608

Using such a flag is not necessarily the best approach, but to answer your specific question: you could make your int volatile. See below a simple example that you can run as is - the fact that i is volatile is crucial for this to work.

The output is (it could be different from run to run due to thread interleaving):

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");
    }
}

Upvotes: 1

bart s
bart s

Reputation: 5100

You might be able to do this with a semaphore

Upvotes: 2

Related Questions