黑马程序员技术交流社区
标题:
关于多线程死锁的一个简单例子
[打印本页]
作者:
EarlyHeart
时间:
2014-7-9 20:55
标题:
关于多线程死锁的一个简单例子
本帖最后由 EarlyHeart 于 2014-7-9 20:58 编辑
public class Demo4 {
public static void main(String[] args) throws InterruptedException {
EatFood e = new EatFood();
Thread t1 = new Thread(e, "张三");
Thread t2 = new Thread(e, "李四");
t1.start();
t2.start();
}
}
class EatFood implements Runnable {
Object o = new Object();
int food = 1000;
public void run() {
while (true) {
synchronized (this) {
//假设同时刻李四来到了这里
synchronized (o) {
if (food > 0)
System.out.println(Thread.currentThread().getName()
+ "抢到了第" + (food--) + "个food");
else
return;
}
}
synchronized (o) {
//假设此时刻张三来到了这里
synchronized (this) {
if (food > 0)
System.out.println(Thread.currentThread().getName()
+ "抢到了第" + (food--) + "个food");
else
return;
}
}
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2