最近我钻研了线程的黑暗艺术,我学会了如何创建它们以及何时使用它们以及何时不使用它们。但是当我试图学习如何沟通它们时,我发现管道是你用来做的。我有一个对象,它是我创建的一个类的实例“,但管道似乎只能发送字节数组或整数。我不会能够使用类似于对象流的东西来将我的对象发送给另一个线程,但是我的网上冲浪已经非常糟糕,我迷路了。所以我猜想唯一要做的就是转向堆栈溢出,看看有没有人可以帮忙。感谢您提前的帮助。与两个线程通信时,我必须使用管道吗?
1
A
回答
5
您应该使用BlockingQueue的实现之一。
我最常使用ArrayBlockingQueue,因为它允许我限制解决方案的内存占用。 A LinkedBlockingDeque可用于无限大小,但请确保您不能超载内存。
这里有两个线程使用ArrayBlockingQueue
来沟通自己。
public class TwoThreads {
public static void main(String args[]) throws InterruptedException {
System.out.println("TwoThreads:Test");
new TwoThreads().test();
}
// The end of the list.
private static final Integer End = -1;
static class Producer implements Runnable {
final BlockingQueue<Integer> queue;
public Producer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
for (int i = 0; i < 1000; i++) {
queue.add(i);
Thread.sleep(1);
}
// Finish the queue.
queue.add(End);
} catch (InterruptedException ex) {
// Just exit.
}
}
}
static class Consumer implements Runnable {
final BlockingQueue<Integer> queue;
public Consumer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
boolean ended = false;
while (!ended) {
try {
Integer i = queue.take();
ended = i == End;
System.out.println(i);
} catch (InterruptedException ex) {
ended = true;
}
}
}
}
public void test() throws InterruptedException {
BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
Thread pt = new Thread(new Producer(queue));
Thread ct = new Thread(new Consumer(queue));
// Start it all going.
pt.start();
ct.start();
// Wait for it to finish.
pt.join();
ct.join();
}
}
+0
这正是我所期待的。这个编程的东西,我只是继续学习!谢谢! – NicholasLupo
相关问题
- 1. 多个线程与管道流进行通信并使用PushbackInputStream
- 2. 我必须使用多少个线程
- 3. C中的管道 - 我必须使用fork吗?
- 4. 使用两个管道的双向进程间通信
- 5. 两个子进程与管道之间进行通信
- 6. epoll:我必须使用多线程
- 7. 我必须使用BreezeController吗?
- 8. 在使用线程时,我绝对必须使用静态变量吗?
- 9. 创建线程时,我们何时必须使用LPTHREAD_START_ROUTINE?
- 10. 我可以使用类变量与线程通信吗?
- 11. 使用管道进行过程通信
- 12. 使用管道的进程间通信
- 13. 进程与管道之间的通信
- 14. 我必须为Posix计时器使用信号处理程序吗?
- 15. 两个子进程通过命名管道进行通信
- 16. 使用管道在多线程程序与孩子沟通
- 17. 使用moq时,我必须知道所有将被使用的方法吗?
- 18. 获取“调用线程必须STA的”使用MVVM光信息
- 19. 必须在单线程程序中使用锁吗?
- 20. 管道通信
- 21. 使用管道与子进程进行通信
- 22. 何时以及为什么我必须关闭管道?
- 23. 管理RHEL更新 - 我必须使用RHN吗?
- 24. 两个线程在两个运行时如何通信?
- 25. 我必须使用Flash Media Encoder吗?
- 26. 我必须使用django注册吗?
- 27. 我必须使用wsgi_module的“def application”吗?
- 28. 我必须使用ContinueWith和HttpClient吗?
- 29. 我必须使用按钮吗?
- 30. 我必须使用连接表吗? [MYSQL]
退房[类似](http://stackoverflow.com/questions/2170520/inter-thread-communication-in-java)[问题](http://stackoverflow.com/questions/9242204/线程间通信)替代选项 –
也有类似的问题,但我找不到一个有我的答案或问我问的问题。 – NicholasLupo
你从哪里得到管道?这似乎离开了左边的领域。你是指不同的过程? – matt