如何保證:如何在線程之間異步傳遞引用?觀察員?
1)localThread
和運行相互獨立的remoteThread
?
2.)在localThread
和remoteThread
之間傳遞消息?
具體來說,localThread
中的字符串對象需要「滲透」到Telnet
,我認爲它被稱爲回調。然而,對於Telnet
到observe
本身沒有任何實質性的東西。這是對LocalIO
的匿名引用,我沒有看到明確提供引用有幫助。
我已閱讀約java.util.concurrent.Semaphore
,直到我的頭爆炸,所有我走開的是,它似乎並不適用。對於這兩個線程,無論其他線程在做什麼,它們都應該繼續運行。但是,需要一些機制來在線程之間傳遞對象引用...
public class Telnet {
public Telnet() throws InterruptedException {
startThreads();
}
public static void main(String[] args) throws InterruptedException {
new Telnet();
}
public void startThreads() throws InterruptedException {
Semaphore s = new Semaphore(1, true);
Thread localThread = new Thread(new LocalIO());
Thread remoteThread = new Thread(new RemoteIO());
localThread.start();
remoteThread.start();
}
}
線程本身如下。 LocalIO
:
public class LocalIO implements Runnable {
@Override
public void run() {
Scanner scanner;
String line;
while (true) {
scanner = new Scanner(System.in);
line = scanner.nextLine();
out.println("\n\nyou entered\t\"" + line + "\"\n");
}
}
}
RemoteIO
:
public class RemoteIO implements Runnable {
private static Logger log = Logger.getLogger(RemoteIO.class.getName());
final String host = "rainmaker.wunderground.com";
final int port = 3000;
@Override
public void run() {
log.fine(host + port);
int byteOfData;
try (Socket socket = new Socket(host, port);
InputStream inputStream = socket.getInputStream();
OutputStream ouputStream = socket.getOutputStream();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
while ((byteOfData = inputStream.read()) != -1) {
out.print((char) byteOfData);
}
} catch (Exception e) {
out.println(e);
}
}
}
牢記RemoteIO
永遠不會關閉它的連接,並無限期地運行。
大聲笑,是的,但一切認真,我會檢查出來,但有**異步** API? – Thufir
我剛剛描述的是異步的。兩個線程都不會等待對方,他們只是繼續他們正在做的事情,並在他們感覺喜歡時檢查新消息。 –