2012-06-03 2 views
0

Пожалуйста, покажите мне, как сделать thread wait. например, ждать, если 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(); 
    } 
} 
+1

, что вы пробовали до сих пор? –

ответ

1

Чтобы избежать активного ожидания попробуйте использовать wait() и notify() или notifyAll() методы. Wait() может сделать нить остановку, пока кто-то не называйте уведомить() или notifyAll() на тот же объект, как ждать(). Один из условия, что нить должна быть в распоряжении монитор объекта, на котором будет ссылаться ждать(), уведомить() или 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 
2

Вы могли бы быть в состоянии сделать это с semaphore

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

Это работает только в течение одного цикла. Если он хочет иметь возможность запускать/приостанавливать/запускать/приостанавливать и т. Д., Это не будет работать так, как есть. – assylias

+0

Вы правы, но вопрос не требовал циклов. –

Смежные вопросы