gpt4 book ai didi

java - 使用观察者模式作为通知程序是否与使用 Thread.join 相同?

转载 作者:搜寻专家 更新时间:2023-10-31 19:58:08 26 4
gpt4 key购买 nike

使用连接等待线程完成与使用观察者在线程完成时通知调用线程类是否相同?

Using join - 

public class Reader {

Thread t = new Thread(new ReadContent());
t.start();
t.join();
System.out.println("Thread has finished");

public class ReadContent() implements Runnable{
}

public void run() {
readContentURL();
}
}

/*****************************************************************************/
Using observer -


public interface ReadContentListener{

public void contentRead();

}


public class Reader implements ReadContentListener {

Thread t = new Thread(new ReadContent(this));
t.start();

pubic void contentRead(){
System.out.println("Thread has finished");
}

public class ReadContent implements Runnable{

public ReadContent(ReadContentListener readContentListener) {
this.readContentListener = readContentListener;
}

public void run() {
readContentURL();
this.readContentListener.contentRead();
}
}


/*************************************************************/

public GenericScreenAnimation(String nextScreen, Thread genericWorkerThread)
{

this.genericWorkerThread = genericWorkerThread;
this.genericWorkerThread.start();
initialise();
try {
this.genericWorkerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ScreenController.displayNextScreen(nextScreen);
}

最佳答案

观察者模式是关于通知其他对象,而不是其他线程。如果阅读已完成,您的 ReadContentListener 将在阅读线程中收到通知。在此期间的原始线程将继续其自己的工作(或完成,如果没有)。

使用 Thread.join 使原始线程简单地阻塞,直到读取线程完成。您通常不会在 .start() 之后直接使用它,但前提是您在原始线程上有其他事情要做,这应该与阅读并行进行。在 .start() 之后直接调用它(对于效果)等同于在原始线程上读取

关于java - 使用观察者模式作为通知程序是否与使用 Thread.join 相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6293542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com