欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA基础----java死锁的一个例子 博客分类: JAVA基础 java thread deadlock 死锁

程序员文章站 2024-03-12 10:43:08
...
java的一个死锁的例子
package com.out.test;

public class Test6 implements Runnable{  
    public static Object o1 = new Object();  
    public static Object o2 = new Object();  
    public static int i = 1;  
    public int flag=1;  
      
    public void run() {  
        System.out.println(i++ + "线程启动。。。。");  
        if (flag == 1) {  
            synchronized(o1) {  
                try {  
                    Thread.sleep(3000);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }
                
                synchronized (o2) {  
                    System.out.println(i + "线程结束");  
                }
            }  
        }    
          
        if (flag == 0) {  
            synchronized(o2) {  
                try {  
                    Thread.sleep(1000);  
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }
                
                synchronized (o1) {  
                    System.out.println(i + "线程结束");  
                } 
            }  
        }  
    }  
      
    public static void main(String[] args) {  
        Test6 lock1 = new Test6();  
        Test6 lock2 = new Test6();  
        lock1.flag = 1;
        lock2.flag = 0;
        Thread thread1 = new Thread(lock1);  
        Thread thread2 = new Thread(lock2);  
          
        thread1.start();  
        thread2.start();  
    }  
}