- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的代码中,我有一个循环,等待某个状态从其他线程更改。另一个线程可以工作,但是我的循环从未看到更改过的值。 它会永远等待。 但是,当我在循环中放入System.out.println
语句时,它突然起作用了!为什么?
以下是我的代码示例:
class MyHouse {
boolean pizzaArrived = false;
void eatPizza() {
while (pizzaArrived == false) {
//System.out.println("waiting");
}
System.out.println("That was delicious!");
}
void deliverPizza() {
pizzaArrived = true;
}
}
deliverPizza()
来设置
pizzaArrived
变量。但是,只有当我取消注释
System.out.println("waiting");
语句时,循环才起作用。这是怎么回事?
最佳答案
允许JVM假定其他线程在循环期间不更改pizzaArrived
变量。换句话说,它可以将pizzaArrived == false
测试提升到循环之外,从而优化此功能:
while (pizzaArrived == false) {}
if (pizzaArrived == false) while (true) {}
volatile
:
volatile boolean pizzaArrived = false;
volatile
变量可确保不同的线程将看到彼此更改对其的影响。这样可以防止JVM缓存
pizzaArrived
的值或在循环外进行测试。相反,它必须每次都读取实变量的值。
volatile
在访问变量之间创建一个事前发生的关系。这意味着,在接收比萨饼的线程中,传递比萨饼之前的
all other work a thread did也可见,即使这些其他更改不是
volatile
变量也是如此。)
volatile
所具有的所有相同副作用。在读取和写入变量时使用它们是使更改对其他线程可见的另一种方法:
class MyHouse {
boolean pizzaArrived = false;
void eatPizza() {
while (getPizzaArrived() == false) {}
System.out.println("That was delicious!");
}
synchronized boolean getPizzaArrived() {
return pizzaArrived;
}
synchronized void deliverPizza() {
pizzaArrived = true;
}
}
System.out
是
PrintStream
对象。
PrintStream
的方法是这样同步的:
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
pizzaArrived
在循环期间被缓存。严格来说,
和两个线程必须在同一对象上同步,以确保对变量的更改是可见的。 (例如,在设置
println
之后调用
pizzaArrived
并在读取
pizzaArrived
之前再次调用它是正确的。)如果只有一个线程在特定对象上同步,则允许JVM忽略它。实际上,JVM不够聪明,无法证明其他线程在设置
println
后不会调用
pizzaArrived
,因此它假定它们可能会调用。因此,如果您调用
System.out.println
,它将无法在循环期间缓存变量。这就是为什么这样的循环在具有打印语句时才起作用的原因,尽管这不是正确的解决方法。
System.out
并不是引起这种效果的唯一方法,而是人们尝试调试其循环为何不起作用时最常发现的一种方法!
while (pizzaArrived == false) {}
是一个忙等待循环。那很糟!等待期间,它占用CPU,这会减慢其他应用程序的速度,并增加系统的电源使用,温度和风扇速度。理想情况下,我们希望循环线程在等待时 hibernate ,因此它不会占用CPU。
Object
:
class MyHouse {
boolean pizzaArrived = false;
void eatPizza() {
synchronized (this) {
while (!pizzaArrived) {
try {
this.wait();
} catch (InterruptedException e) {}
}
}
System.out.println("That was delicious!");
}
void deliverPizza() {
synchronized (this) {
pizzaArrived = true;
this.notifyAll();
}
}
}
wait()
,使线程进入休眠状态。 hibernate 时将不使用任何CPU周期。在第二个线程设置变量之后,它将调用
notifyAll()
唤醒正在该对象上等待的所有线程。这就像让比萨饼人按门铃一样,因此您可以在等待时坐下来休息,而不必笨拙地站在门口。
this
(
MyHouse
的实例)。通常,两个线程将无法同时输入同一对象的同步块(synchronized block)(这是同步目的的一部分),但是它在这里起作用,因为一个线程在
wait()
方法内部时会暂时释放同步锁。
BlockingQueue
用于实现生产者-消费者队列。 “消费者”从队列的最前面取物品,“生产者”在队列的最后面取物品。一个例子:
class MyHouse {
final BlockingQueue<Object> queue = new LinkedBlockingQueue<>();
void eatFood() throws InterruptedException {
// take next item from the queue (sleeps while waiting)
Object food = queue.take();
// and do something with it
System.out.println("Eating: " + food);
}
void deliverPizza() throws InterruptedException {
// in producer threads, we push items on to the queue.
// if there is space in the queue we can return immediately;
// the consumer thread(s) will get to it later
queue.put("A delicious pizza");
}
}
put
的
take
和
BlockingQueue
方法会抛出
InterruptedException
,这是必须处理的检查异常。在上面的代码中,为简单起见,重新抛出了异常。您可能希望在方法中捕获异常,然后重试put或take调用以确保成功。除了这一点之外,
BlockingQueue
非常易于使用。
BlockingQueue
确保将线程放入队列之前执行的所有操作对于将这些线程取出的线程都是可见的。
Executor
类似于执行任务的现成的
BlockingQueue
。例子:
// A "SingleThreadExecutor" has one work thread and an unlimited queue
ExecutorService executor = Executors.newSingleThreadExecutor();
Runnable eatPizza = () -> { System.out.println("Eating a delicious pizza"); };
Runnable cleanUp = () -> { System.out.println("Cleaning up the house"); };
// we submit tasks which will be executed on the work thread
executor.execute(eatPizza);
executor.execute(cleanUp);
// we continue immediately without needing to wait for the tasks to finish
Executor
,
ExecutorService
和
Executors
的文档。
JLabel label = new JLabel();
JButton button = new JButton("Click me");
button.addActionListener((ActionEvent e) -> {
// This event listener is run when the button is clicked.
// We don't need to loop while waiting.
label.setText("Button was clicked");
});
BlockingQueue
或
Executor
)调度到等待的线程。您还可以使用为此专门设计的
SwingWorker
,并自动提供一个后台工作线程:
JLabel label = new JLabel();
JButton button = new JButton("Calculate answer");
// Add a click listener for the button
button.addActionListener((ActionEvent e) -> {
// Defines MyWorker as a SwingWorker whose result type is String:
class MyWorker extends SwingWorker<String,Void> {
@Override
public String doInBackground() throws Exception {
// This method is called on a background thread.
// You can do long work here without blocking the UI.
// This is just an example:
Thread.sleep(5000);
return "Answer is 42";
}
@Override
protected void done() {
// This method is called on the Swing thread once the work is done
String result;
try {
result = get();
} catch (Exception e) {
throw new RuntimeException(e);
}
label.setText(result); // will display "Answer is 42"
}
}
// Start the worker
new MyWorker().execute();
});
java.util.Timer
。它比编写自己的定时循环更容易使用,并且更容易启动和停止。该演示每秒打印一次当前时间:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println(System.currentTimeMillis());
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
java.util.Timer
都有其自己的后台线程,该线程用于执行其计划的
TimerTask
。自然地,线程在任务之间 hibernate ,因此它不会占用CPU。
javax.swing.Timer
,它类似于,但是它在Swing线程上执行监听器,因此您可以安全地与Swing组件进行交互,而无需手动切换线程:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer timer = new Timer(1000, (ActionEvent e) -> {
frame.setTitle(String.valueOf(System.currentTimeMillis()));
});
timer.setRepeats(true);
timer.start();
frame.setVisible(true);
关于java - 没有打印语句,循环看不到其他线程更改的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48657316/
有没有更好的方法用 PHP 将数据输出到 html 页面? 如果我想在 php 中用一些 var 制作一个 div,我会写类似的东西 print (''.$var.''); 或 echo "''.$v
我可以使用 java awt print 来打印文档/文件而不是使用 javax print 吗?我发现在 java awt print 中有一个选项可以使用 AttributedString 将内容
目前我通过以下方式运行 R 脚本: R --slave argument1 argument2 ... 我想知道 R 中关于如何退出脚本并发出警告的最佳实践,q() 会这样做吗? if(!file.
谁能告诉我如何编写一个程序,用 gcc 编译时打印 c ,用 g++ 编译时打印 c++? 最佳答案 #ifdef __cplusplus printf("c++\n"); #else
我需要支持在 KitKat 设备上打印,但我的目标 SDK 是 13(无法更改)。 特别是我需要打印一个 webview。 这是用于打印 webview 的 API: http://developer
我正在尝试创建一个简单的函数,其中 python 将根据您的年份输入计算年龄。我已经尝试了几种方法,但我没有运气 atm。 附:对不起,我是新手。 ame = input(" Enter your n
JavaFX 2.0 是否支持打印?我有一个文本区域,我从中获取文本然后我想打印它,但似乎没有这个功能。 当然,这里我说的是打印到打印机。 :) 最佳答案 尚不支持。作为一种解决方法,您可以使用 Ja
我试图找出printOn的重点。我查看了一些实现它的类,看起来它只是帮助打印不同数据类型的单位。这是准确的吗? 如果是这样,有人能指出我如何为我自己的类(class)实现这一点的正确方向吗?我将在可能
我无法让 IE 打印我的 Canvas (使用 excanvas 生成)...我使用的是最新版本的 excanvas。 http://dl.dropbox.com/u/997831/canvas.ht
我搜索了很多但没有人回答我的问题,我读到在这样的信号处理程序中使用 cout 是不安全的: void ctrlZHandler(int sig_num) { //SIGTSTP-18
我有兴趣打印一系列查询。我有以下代码。 start = datetime.datetime(2012, 2, 2, 6, 35, 6, 764) end = datetime.datetime(201
public class javaClass { public static void main(String [] arg) { String row1 = "A____A"
我需要写入前一行的命令,例如不带\n 的 print()。 下面是一些示例代码: a=0 print("Random string value") if a==0: print_to_prev
我有一个使用 UIKit 和 Objective C 的旧 iOS 应用程序,我目前正在将其移植到 SwiftUI 和 Swift。一切都很顺利,我喜欢 Swift 和 SwiftUI。该应用程序已经
我创建了一个求和函数,它接受一个开始编号和一个结束编号,并返回这两点之间的总和答案 def print_sum_equations(start_number,end_number):
在 Perl 6 中,print 和有什么区别? , put和 say ? 我怎么看 print 5不同,但 put 5和 say 5看起来一样。 最佳答案 put $a就像 print $a.Str
我正在使用 here 中的 getOrgChart 库,我正在尝试打印整个图表,而不仅仅是可见部分。不幸的是,当使用标准库打印功能时,它只会打印出第一部分,而我不知道如何打印整个图表(该图表相当宽,大
我制作了一个非常适合 A4 页面的 View 。现在我想打印它。请注意,我没有使用drawRect或类似的东西,只是一个带有 subview 和文本标签的普通 View 。我的问题是,我对该 View
由于 Cocoa-Java 已弃用,我正在将 Cocoa-Java 代码迁移到 Cocoa + JNI。该代码打印存储在文件中的图像。新的 Cocoa 代码基本上是: NSImage *image =
这个问题已经有答案了: Printing a TDBGrid (4 个回答) 已关闭 6 年前。 如何在不安装或下载组件的情况下打印 DBGrid? 或者 如何将 DBGrid 的数据放入 RichE
我是一名优秀的程序员,十分优秀!