- 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,这会降低其他应用程序的速度,并增加系统的电源使用,温度和风扇速度。理想情况下,我们希望循环线程在等待时休眠,因此它不会占用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()
,这使线程进入睡眠状态。休眠时将不使用任何CPU周期。在第二个线程设置变量后,它调用
notifyAll()
唤醒正在该对象上等待的所有线程。这就像让比萨饼人按门铃一样,因此您可以在等待时坐下来休息,而不必笨拙地站在门口。
this
(
MyHouse
的实例)。通常,两个线程将无法同时输入同一对象的同步块(这是同步目的的一部分),但它在这里起作用,因为一个线程在
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
。自然地,线程在任务之间休眠,因此它不会占用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/62195073/
创建一个“海盗对话”,可以选择左手或右手。我希望它对“左”和“右”的不同拼写做出积极的回答(正如您将在代码中看到的那样),但是,当我为所有非“右”或“左”的输入添加最终的“else”代码时,它给了我一
With 语句 对一个对象执行一系列的语句。 With object statements End With 参数 object 必需的部分
While...Wend 语句 当指定的条件为 True 时,执行一系列的语句。 While condition  ; Version [stat
所以我正在处理的代码有一个小问题。 while True: r = input("Line: ") n = r.split() if r == " ":
我有一个对象数组: var contacts = [ { "firstName": "Akira", "lastName": "Laine", "number"
int main() { int f=fun(); ... } int fun() { return 1; return 2; } 在上面的程序中,当从main函数中调用一个
我的项目中有很多 if 语句、嵌套 if 语句和 if-else 语句,我正在考虑将它们更改为 switch 语句。其中一些将具有嵌套的 switch 语句。我知道就编译而言,switch 语句通常更
Rem 语句 包含程序中的解释性注释。 Rem comment 或 ' comment comment 参数是需要包含的注释文本。在 Rem 关键字和 comment 之间应有一个空格。
ReDim 语句 在过程级中声明动态数组变量并分配或重新分配存储空间。 ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
Randomize 语句 初始化随机数生成器。 Randomize [number] number 参数可以是任何有效的数值表达式。 说明 Randomize 使用 number 参数初始
Public 语句 定义公有变量并分配存储空间。在 Class 块中定义私有变量。 Public varname[([subscripts])][, varname[([subscripts])
Sub 语句 声明 Sub 过程的名称、参数以及构成其主体的代码。 [Public [Default]| Private] Sub name [( arglist )]
Set 语句 将对象引用赋给一个variable或property,或者将对象引用与事件关联。 Set objectvar = {objectexpression | New classname
我有这个代码块,有时第一个 if 语句先运行,有时第二个 if 语句先运行。我不确定为什么会这样,因为我认为 javascript 是同步的。 for (let i = 0; i < dataObje
这是一个 javascript 代码,我想把它写成这样:如果此人回答是,则回复“那很酷”,如果此人回答否,则回复“我会让你开心”,如果此人回答的问题包含"is"或“否”,请说“仅键入”是或否,没有任何
这是我的任务,我尝试仅使用简短的 if 语句来完成此任务,我得到的唯一错误是使用“(0.5<=ratio<2 )”,除此之外,构造正确吗? Scanner scn = new Scanner(
有没有办法在 select 语句中使用 if 语句? 我不能在这个中使用 Case 语句。实际上我正在使用 iReport 并且我有一个参数。我想要做的是,如果用户没有输入某个参数,它将选择所有实例。
这个问题在这里已经有了答案: 关闭 11 年前。 Possible Duplicate: If vs. Switch Speed 我将以 C++ 为例,但我要问的问题不是针对特定语言的。我的意思是一
Property Set 语句 在 Class 块中,声明名称、参数和代码,这些构成了将引用设置到对象的 Property 过程的主体。 [Public | Private] Pro
Property Let 语句 在 Class 块中,声明名称、参数和代码等,它们构成了赋值(设置)的 Property 过程的主体。 [Public | Private] Prop
我是一名优秀的程序员,十分优秀!