8

我想知道如何通知另一个线程的最佳方式。例如,我有一个后台线程:

public void StartBackgroundThread(){
new Thread(new Runnable() {         
        @Override
        public void run() {
            //Do something big...
            //THEN HOW TO NOTIFY MAIN THREAD?
        }
    }).start();
}

当它完成时它必须通知主线程?如果有人知道如何做到这一点的最佳方法,我将不胜感激!

4

5 回答 5

3

典型的答案是BlockingQueue. 两者BackgroundThread(通常称为生产者)和MainThread(通常称为消费者)共享队列的单个实例(也许它们在实例化时得到它)。每次有新消息时调用并BackgroundThread调用“queue.take() BlockingQueue ArrayBlockingQueue”。queue.put(message)MainThreadwhich will block until there's a message to receive. You can get fancy with timeouts and peeking but typically people want ainstance such as

于 2013-01-15T01:55:13.337 回答
3

纯粹基于您的问题,您可以这样做:

public class test
{
  Object syncObj = new Object();

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

  public test()
  {
    startBackgroundThread();

    System.out.println("Main thread waiting...");
    try
    {
      synchronized(syncObj)
      {
        syncObj.wait();
      }
    }
    catch(InterruptedException ie) { }
    System.out.println("Main thread exiting...");
  }

  public void startBackgroundThread()
  {
    (new Thread(new Runnable()
    {
      @Override
      public void run()
      {
        //Do something big...
        System.out.println("Background Thread doing something big...");
        //THEN HOW TO NOTIFY MAIN THREAD?
        synchronized(syncObj)
        {
          System.out.println("Background Thread notifing...");
      syncObj.notify();
        }
        System.out.println("Background Thread exiting...");
      }
    })).start();
  }
}

并看到这个输出

PS C:\Users\java> javac test.java
PS C:\Users\java> java test
Main thread waiting...
Background Thread doing something big...
Background Thread notifing...
Background Thread exiting...
Main thread exiting...
于 2013-01-15T03:47:23.333 回答
1

只需调用 notify()

public void run() { 
    try { 
        while ( true ) { 
            putMessage(); 
            sleep( 1000 ); 
        } 
    }  
    catch( InterruptedException e ) { } 
} 

private synchronized void putMessage() throws InterruptedException { 
    while ( messages.size() == MAXQUEUE ) 
        wait(); 

    messages.addElement( new java.util.Date().toString() ); 
    notify(); 
} 
于 2013-01-15T01:21:47.087 回答
1

您不能“通知主线程”。

最好的方法是使用ExecutorService,例如:

 import java.util.concurrent.*;

 // in main thread
 ExecutorService executorService = Executors.newSingleThreadExecutor();

 Future<?> future = executorService.submit(new Runnable() {         
    @Override
    public void run() {
        //Do something big...
    }
});

future.get(); // blocks until the Runnable finishes

这些类是专门为处理异步操作而编写的,并且其中的所有代码都已经为您编写好了并且是防弹的。

编辑

如果您不想在等待时阻塞主线程,请在另一个线程中等待:

 final Future<?> future = executorService.submit(new Runnable() {         
    @Override
    public void run() {
        //Do something big...
    }
});

new Thread(new Runnable() {         
    @Override
    public void run() {
        future.get(); // blocks until the other Runnable finishes
        // Do something after the other runnable completes
    }
}).start();
于 2013-01-15T02:00:28.570 回答
0

一个线程通知另一个线程不是一个好方法。最好有 1 个主线程让从属线程工作。从属线程始终在运行并等待直到它收到工作。我建议您绘制两列并准确确定每个线程需要等待的位置。

    public void run() 
    {
    //Do something big...
    synchronized(this)
    {
        done = true;
    }
    }

Java 包括使这一点非常容易看到的库ExecutorService和以下帖子 Producer/Consumer threads using a Queue

于 2013-01-15T01:23:04.947 回答