简体   繁体   English

PrintWriter等待和通知方法做什么?

[英]PrintWriter what do wait and notify methods do?

I read android documentation (which is clear as mud) and it says that: 我阅读了android文档(很明显是泥巴),它说:

wait 等待

Causes the calling thread to wait until another thread calls the notify() or notifyAll() method of this object. 使调用线程等待,直到另一个线程调用此对象的notify()或notifyAll()方法。

notify 通知

Causes a thread which is waiting on this object's monitor (by means of calling one of the wait() methods) to be woken up. 导致唤醒正在此对象的监视器上等待的线程(通过调用wait()方法之一)。

Does that mean that: 这是否意味着:

public synchronized void myAwesomeFunction (PrintWriter out, String[] data)
{
    for (String d : data)
    {
        out.wait();
        out.println (d);
        out.flush();
        out.notify();
    }
}

would wait until PrintWriter finish sending the first string and then move to the next one? 会等到PrintWriter完成发送第一个字符串然后移至下一个字符串? or did i get it completely wrong? 还是我完全弄错了?

Every object in Java can be used as a lock. Java中的每个对象都可以用作锁。 These methods are inherited from the Object class, and are useful for synchronization between threads. 这些方法是从Object类继承的,对于线程之间的同步很有用。 They are completely unrelated to the PrintWriter functionality. 它们与PrintWriter功能完全无关。

println() is a blocking function - it does not return until it has finished sending the first string (ignoring buffering). println()是一个阻塞函数-它直到完成发送第一个字符串(忽略缓冲)后才会返回。 Simply writing this: 简单地写这个:

out.println(d);
System.out.println("'d' has finished writing");

Is all you need to achieve the same effect. 是您达到相同效果所需的全部。 Using wait and notify is useful when you want one thread to wait for another, and is not normally useful within the same thread. 当您希望一个线程等待另一个线程时,使用wait and notify很有用,通常在同一线程中没有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM