如何在 Java 多线程中从线程 2 设置线程 1 的布尔标志
问题描述
我正在编写一个简单的 multithreaded
应用程序,它涉及三个线程:Thread-1
、Thread-2
和 main
.
I am writing a simple multithreaded
application that involves three threads:
Thread-1
, Thread-2
and main
.
Thread-1
是一个 random number
生成器类,它产生 random doubles
并提供给 线程 2
.
Thread-1
is a random number
generator class that produces random doubles
and feeds to Thread-2
.
Thread-2
消耗 的数字来计算平均值.我使用了 PipedOutputStream
那 Thread-1
随机数
.Thread-2
使用 PipedInputStream
吃掉 随机数
.
Thread-2
consumes the numbers to calculate the average .I have used PipedOutputStream
that Thread-1
feeds with random numbers
. Thread-2
uses PipedInputStream
to eat up the random numbers
.
问题是::
如果 Thread-2
中的平均值超过 1E5,我想向 Thread-1
发出信号以停止生成数字.我在 Thread-1
中有一个 boolean flag
需要打开.我怎样才能做到这一点?
if the average exceeds 1E5 in Thread-2
, I want to signal Thread-1
to stop producing numbers. I have a boolean flag
in Thread-1
that needs to be turned on. How can I achieve this?
PS:代码永远运行,没有在控制台上打印任何东西,我还没有弄清楚为什么!!
PS: The code as it is runs forever without printing anything on console which I am yet to figure out why!!
推荐答案
您可以使用 AtomicBoolean
并将其传递给两个线程,原子类型是可访问的,多线程也是线程安全的.
You could use AtomicBoolean
and pass it to the both threads, Atomic types is accessable throw multithreading also thread safe.
首先声明你将 isDone
标记为 AtomicBoolean
first declare you flag isDone
as AtomicBoolean
然后声明一个 AtomicBoolean
对象并将其传递给两个线程
then declare one AtomicBoolean
object and pass it to the both threads
最后,一旦你想停止生成数字,要求 Thread-2
将 isDone
设置为 false.
finally once you want to stop generting numbers ask Thread-2
to set the isDone
false.
这篇关于如何在 Java 多线程中从线程 2 设置线程 1 的布尔标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!