The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. 死锁描述了两个或多个线程被永远阻塞,彼此等待的情况。Here's an example.这里有一个例子。
Alphonse and Gaston are friends, and great believers in courtesy. 阿尔方斯和加斯顿是朋友,非常相信礼貌。A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. 礼貌的一条严格规则是,当你向朋友鞠躬时,你必须保持鞠躬,直到你的朋友有机会回敬你。Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time. 不幸的是,这条规则没有考虑到两个朋友同时向对方鞠躬的可能性。This example application, 此示例应用程序
, models this possibility:Deadlock
模拟了这种可能性:Deadlock
public class Deadlock { static class Friend { private final String name; public Friend(String name) { this.name = name; } public String getName() { return this.name; } public synchronized void bow(Friend bower) { System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName()); bower.bowBack(this); } public synchronized void bowBack(Friend bower) { System.out.format("%s: %s" + " has bowed back to me!%n", this.name, bower.getName()); } } public static void main(String[] args) { final Friend alphonse = new Friend("Alphonse"); final Friend gaston = new Friend("Gaston"); new Thread(new Runnable() { public void run() { alphonse.bow(gaston); } }).start(); new Thread(new Runnable() { public void run() { gaston.bow(alphonse); } }).start(); } }
When 当Deadlock
runs, it's extremely likely that both threads will block when they attempt to invoke bowBack
. Deadlock
运行时,两个线程在试图调用bowBack
时极有可能都会阻塞。Neither block will ever end, because each thread is waiting for the other to exit 两个块都不会结束,因为每个线程都在等待另一个退出bow
.bow
。