本帖最后由 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;
- }
- }
- }
- }
- }
复制代码
|
|