JVM 可以假设其他线程不会改变pizzaArrived
循环期间的变量。换句话说,它可以提升pizzaArrived == false
在循环外进行测试,优化此:
while (pizzaArrived == false) {}
进入这个:
if (pizzaArrived == false) while (true) {}
这是一个无限循环。
为了确保一个线程所做的更改对其他线程可见,您必须始终添加一些同步线程之间。最简单的方法是创建共享变量volatile
:
volatile boolean pizzaArrived = false;
制作一个变量volatile
保证不同的线程能够看到彼此的更改的效果。这可以防止 JVM 缓存以下值pizzaArrived
或将测试提升到循环之外。相反,它每次都必须读取实变量的值。
(更正式地说,volatile
创建一个发生在之前变量访问之间的关系。这意味着线程所做的所有其他工作 https://stackoverflow.com/questions/19738651/volatile-variable-explanation-in-java-docs在交付披萨之前对于接收披萨的线程也是可见的,即使那些其他更改不volatile
变量。)
同步方法 http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html主要用于实现互斥(防止两件事同时发生),但它们也具有与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;
}
}
print语句的效果
System.out
is a PrintStream
目的。的方法PrintStream
像这样同步:
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
同步可以防止pizzaArrived
在循环期间被缓存。严格来讲,both线程必须在同一个对象上同步以保证变量的更改是可见的。 (例如,调用println
设置后pizzaArrived
并在阅读之前再次调用它pizzaArrived
是正确的。)如果只有一个线程在某一特定对象上进行同步,则 JVM 可以忽略它。在实践中,JVM不够聪明,无法证明其他线程不会调用println
设置后pizzaArrived
,所以它假设他们可能会。因此,如果您调用,它无法在循环期间缓存变量System.out.println
。这就是为什么像这样的循环在有 print 语句时可以工作,尽管这不是正确的解决方案。
Using System.out
并不是导致这种效果的唯一方法,但这是人们在尝试调试循环不起作用的原因时最常发现的方法!
更大的问题
while (pizzaArrived == false) {}
是一个忙等待循环。那很糟!在等待时,它会占用 CPU,从而减慢其他应用程序的速度,并增加系统的功耗、温度和风扇速度。理想情况下,我们希望循环线程在等待时休眠,这样它就不会占用 CPU。
以下是一些方法:
使用等待/通知
一个低级的解决方案是使用等待/通知方法Object https://stackoverflow.com/questions/2536692/a-simple-scenario-using-wait-and-notify-in-java:
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() http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--,这会使线程休眠。它在睡眠时不会使用任何 CPU 周期。第二个线程设置变量后,它调用notifyAll() http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#notifyAll--唤醒正在等待该对象的任何/所有线程。这就像让披萨师傅按门铃,这样你就可以在等待时坐下来休息,而不是尴尬地站在门口。
当对一个对象调用 wait/notify 时,您必须持有该对象的同步锁,这就是上面代码的作用。你可以使用任何你喜欢的对象,只要两个线程使用同一个对象:这里我使用this
(实例MyHouse
)。通常,两个线程不能同时进入同一个对象的同步块(这是同步目的的一部分),但它在这里可以工作,因为线程在其内部时会暂时释放同步锁。wait()
method.
阻塞队列
A BlockingQueue http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html用于实现生产者-消费者队列。 “消费者”从队列的前面取出物品,“生产者”在队列的后面推送物品。一个例子:
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
and take
的方法BlockingQueue
可以扔InterruptedException
s,这是必须处理的检查异常。在上面的代码中,为了简单起见,重新抛出了异常。您可能更愿意捕获方法中的异常并重试 put 或 take 调用以确保其成功。除了这一点丑之外,BlockingQueue
非常容易使用。
这里不需要其他同步,因为BlockingQueue
确保线程在将项目放入队列之前所做的一切对于取出这些项目的线程可见。
执行者
Executor
s 就像现成的BlockingQueue
执行任务的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 http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html, ExecutorService http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html, and Executors http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html.
事件处理
在等待用户单击 UI 中的某些内容时循环是错误的。相反,请使用 UI 工具包的事件处理功能。In Swing http://docs.oracle.com/javase/tutorial/uiswing/events/index.html, 例如:
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 的其他交互,直到工作完成。慢速操作可以在新线程上启动,或者使用上述技术之一(等待/通知、BlockingQueue
, or Executor
)。您还可以使用SwingWorker http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html,它就是专门为此设计的,并自动提供后台工作线程:
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();
});
Timers
要执行定期操作,您可以使用java.util.Timer http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html。它比编写自己的定时循环更容易使用,并且更容易启动和停止。该演示每秒打印一次当前时间:
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
System.out.println(System.currentTimeMillis());
}
};
timer.scheduleAtFixedRate(task, 0, 1000);
Each java.util.Timer
有自己的后台线程,用于执行其预定的TimerTask
s。当然,线程在任务之间会休眠,因此不会占用 CPU。
在Swing代码中,还有一个javax.swing.Timer http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html,类似,但它在 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 http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html
- java.util.concurrent.atomic http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
- java.util.concurrent.locks http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/package-summary.html
并且还可以看到并发部分 http://docs.oracle.com/javase/tutorial/essential/concurrency/index.htmlJava 教程。多线程很复杂,但有很多帮助可用!