Getting the output of a Thread

后端 未结 7 1523
时光说笑
时光说笑 2021-02-02 01:28

What do you think is the best way for obtaining the results of the work of a thread? Imagine a Thread which does some calculations, how do you warn the main program the calculat

7条回答
  •  攒了一身酷
    2021-02-02 01:28

    Polling a.k.a busy waiting is not a good idea. As you mentioned, busy waiting wastes CPU cycles and can cause your application to appear unresponsive.

    My Java is rough, but you want something like the following:

    If one thread has to wait for the output of another thread you should make use of a condition variable.

    final Lock lock = new ReentrantLock();
    final Condition cv = lock.newCondition();
    

    The thread interested in the output of the other threat should call cv.wait(). This will cause the current thread to block. When the worker thread is finished working, it should call cv.signal(). This will cause the blocked thread to become unblocked, allowing it to inspect the output of the worker thread.

提交回复
热议问题