简体   繁体   English

我如何在 Java 中为我的 2 个线程计时

[英]how can i time my 2 threads in java

I have 2 threads, one to take Orders and the other one to distribute the orders.我有 2 个线程,一个用于接受订单,另一个用于分发订单。

My first thread must be able to get the orders gradually one by one from a file and display it in a JTextArea-1, while this is happening the other thread should be able to remove one order at a time from JTextArea-1 and paste it to another JTextArea-2.我的第一个线程必须能够从文件中逐步获取订单并将其显示在 JTextArea-1 中,而发生这种情况时,另一个线程应该能够一次从 JTextArea-1 中删除一个订单并粘贴它到另一个 JTextArea-2。

I have created 2 threads and used MVC pattern (with 2 views and 1 model).我创建了 2 个线程并使用了 MVC 模式(有 2 个视图和 1 个模型)。 The Threads are both displaying the values in the JTEXTAREA's at the same time which is not acceptable.线程同时显示 JTEXTAREA 中的值,这是不可接受的。 How can i solve this issue?我该如何解决这个问题?

I should have a minimum 5 seconds delay between the removing from JTextArea-1 and pasting into JTextArea-2.在从 JTextArea-1 中删除和粘贴到 JTextArea-2 之间,我应该至少有 5 秒的延迟。 kindly help.请帮助。

Fundamental lack of comprehension of concurrency alert!对并发的理解根本不够警惕!

This is not the appropriate way to deal with your problem, which probably doesn't even need threads in the first place.这不是处理您的问题的合适方法,它可能一开始甚至不需要线程。

But if you insist on using threads, what you want is a semaphore to block one thread until a condition for the other thread to act exists.但是如果你坚持使用线程,你想要的是一个信号量来阻塞一个线程,直到另一个线程执行的条件存在。 A "FIFO blocking queue" would be appropriate here as well. “FIFO 阻塞队列”在这里也很合适。

Using pauses and timing with concurrency is not effective as it is a non-deterministic system, and only lead to even more subtle failure scenarios.使用并发暂停计时是无效的,因为它是一个不确定的系统,只会导致更微妙的故障场景。

您可以简单地添加一个记录文本的synchronized调用,以便一次只有 1 个线程可以执行该调用。

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

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