gpt4 book ai didi

java - 没有打印语句,循环看不到其他线程更改的值

转载 作者:行者123 更新时间:2023-12-04 13:06:33 25 4
gpt4 key购买 nike

在我的代码中,我有一个循环,等待某个状态从其他线程更改。另一个线程可以工作,但是我的循环从未看到更改过的值。它永远等待。但是,当我将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;
}
}


在while循环运行时,我从另一个线程调用 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变量。)

Synchronized methods主要用于实现互斥(防止同时发生两件事),但它们也具有与 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.outPrintStream对象。 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。

以下是一些方法:

使用等待/通知

一个较低的解决方案是 use the wait/notify methods of 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()唤醒正在该对象上等待的所有线程。这就像让比萨饼人按门铃一样,因此您可以在等待时坐下来休息,而不必笨拙地站在门口。

当在对象上调用wait / notify时,您必须持有该对象的同步锁,以上代码就是这样做的。您可以使用任何您喜欢的对象,只要两个线程使用同一个对象即可:在这里,我使用了 thisMyHouse的实例)。通常,两个线程将无法同时输入同一对象的同步块(这是同步目的的一部分),但是它在这里起作用,因为一个线程在 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");
}
}


注意: puttakeBlockingQueue方法可以抛出 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


有关详细信息,请参见 ExecutorExecutorServiceExecutors的文档。

事件处理

等待用户单击UI中的内容时循环播放是错误的。而是使用UI工具包的事件处理功能。 In Swing,例如:

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");
});


因为事件处理程序在事件分发线程上运行,所以在事件处理程序中进行长时间的工作会阻止与UI的其他交互,直到工作完成。慢速操作可以在新线程上启动,也可以使用上述一种技术(wait / notify, BlockingQueueExecutor)分派到等待的线程。您还可以使用专门为此设计的 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。

在Swing代码中,还有一个 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.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks


另请参阅Java教程的 Concurrency section。多线程很复杂,但是有很多可用的帮助!

关于java - 没有打印语句,循环看不到其他线程更改的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30089407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com