- package threadDemos;
- class DeadLockRunnable implements Runnable
- {
- static Object chopsticks = new Object();
- static Object knifeAndFork = new Object();
-
- private boolean flag;
- DeadLockRunnable (boolean flag)
- {
- this.flag = flag;
- }
- @Override
- public void run() {
- if(flag)
- {
- while(true)
- {
-
- synchronized (chopsticks) {
-
- System.out.println(Thread.currentThread().
- getName()+"-------Give me the knife!");
-
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- synchronized (knifeAndFork) {
-
- System.out.println(Thread.currentThread().
- getName()+"-------Give me the chopsticks!");
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- }
- }
- else
- {
- while(true)
- {
- synchronized (knifeAndFork) {
-
- System.out.println(Thread.currentThread().
- getName()+"-------Give me the chopsticks!");
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- synchronized (chopsticks) {
-
- System.out.println(Thread.currentThread().
- getName()+"-------Give me the knife!");
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- }
- }
-
- }
-
-
-
- }
- public class DieLockDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- //创建两个DeadLockRunnable对象
- DeadLockRunnable dlr = new DeadLockRunnable(true);
- DeadLockRunnable dlr2 = new DeadLockRunnable(false);
- //创建并开启两个线程
- new Thread(dlr,"Chinese").start();
- new Thread(dlr2,"America").start();
-
- }
- }
复制代码
困扰我好久,都不知道这是不是死锁,怎么看出来是不是死锁呢?求赐教,
部分执行结果如下:
Chinese-------Give me the knife!
America-------Give me the chopsticks!
America-------Give me the knife!
Chinese-------Give me the chopsticks!
Chinese-------Give me the knife!
America-------Give me the chopsticks!
America-------Give me the knife!
Chinese-------Give me the chopsticks!
America-------Give me the chopsticks!
Chinese-------Give me the knife!
Chinese-------Give me the chopsticks!
America-------Give me the knife!
America-------Give me the chopsticks!
Chinese-------Give me the knife!
America-------Give me the knife!
Chinese-------Give me the chopsticks! |
|