pizzaArrived
JVM 可以假设其他线程在循环期间不会更改变量。换句话说,它可以将pizzaArrived == false
测试提升到循环之外,从而优化:
while (pizzaArrived == false) {}
进入这个:
if (pizzaArrived == false) while (true) {}
这是一个无限循环。
为了确保一个线程所做的更改对其他线程可见,您必须始终在线程之间添加一些同步。最简单的方法是创建共享变量volatile
:
volatile boolean pizzaArrived = false;
制作一个变量volatile
可以保证不同的线程将看到彼此更改它的效果。这可以防止 JVMpizzaArrived
在循环外缓存或提升测试的值。相反,它必须每次都读取实变量的值。
(更正式地说,在对变量的访问之间volatile
创建发生前的关系。这意味着线程在交付比萨饼之前所做的所有其他工作对于接收比萨饼的线程也是可见的,即使这些其他更改不是针对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
. 这就是为什么像这样的循环在有 print 语句时会起作用,尽管它不是正确的修复方法。
使用System.out
不是导致这种效果的唯一方法,但它是人们最常发现的一种方法,当他们试图调试为什么他们的循环不起作用时!
更大的问题
while (pizzaArrived == false) {}
是一个忙等待循环。那很糟!在等待期间,它会占用 CPU,从而减慢其他应用程序的速度,并增加系统的功耗、温度和风扇速度。理想情况下,我们希望循环线程在等待时休眠,这样它就不会占用 CPU。
以下是一些方法:
使用等待/通知
一个低级的解决方案是使用 wait/notify 方法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 时,您必须持有该对象的同步锁,这就是上面的代码所做的。你可以使用任何你喜欢的对象,只要两个线程都使用同一个对象:这里我使用this
了(的实例MyHouse
)。通常,两个线程不能同时进入同一个对象的同步块(这是同步目的的一部分),但它在这里可以工作,因为线程在wait()
方法内部时会临时释放同步锁。
阻塞队列
ABlockingQueue
用于实现生产者-消费者队列。“消费者”从队列的前面取出物品,而“生产者”将物品推到队列的后面。一个例子:
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");
}
}
注意:can throw的put
andtake
方法是必须处理的已检查异常。在上面的代码中,为简单起见,异常被重新抛出。您可能更喜欢在方法中捕获异常并重试 put 或 take 调用以确保它成功。除了那一点丑,还是很容易上手的。BlockingQueue
InterruptedException
BlockingQueue
这里不需要其他同步,因为 aBlockingQueue
确保线程在将项目放入队列之前所做的所有事情对于取出这些项目的线程都是可见的。
执行者
Executor
BlockingQueue
s 就像执行任务的现成的s。例子:
// 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
。
事件处理
在等待用户单击 UI 中的某些内容时循环是错误的。相反,请使用 UI 工具包的事件处理功能。在 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 的其他交互,直到工作完成。可以在新线程上启动慢速操作,或者使用上述技术之一(等待/通知、aBlockingQueue
或Executor
)将慢速操作分派到等待线程。您还可以使用SwingWorker
专门为此设计的 a ,并自动提供后台工作线程:
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
的 s。自然,线程在任务之间休眠,因此它不会占用 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 教程的并发部分。多线程很复杂,但有很多可用的帮助!