线程死锁-死锁产生演练

   日期:2020-06-02     浏览:97    评论:0    
核心提示:线程死锁代码演练demo:package cn.yb.thread;public class DeadLockRunnable implements Runnable { private int flag;//决定线程走向的标记 private static Object obj1 = new Object();//锁对象1 private static Object obj2 = new Object();//锁对象2 public DeadLockR.
线程死锁


代码演练demo:

package cn.yb.thread;

public class DeadLockRunnable implements Runnable {
    private int flag;//决定线程走向的标记
    private static Object obj1 = new Object();//锁对象1
    private static Object obj2 = new Object();//锁对象2
    
    public DeadLockRunnable(int flag) {
    	this.flag = flag;
    }
    
	public void run() {
		if(flag == 1){
		 //线程1执行代码 
		  synchronized (obj1) {
			System.out.println(Thread.currentThread().getName()+"已经获取到资源obj1,请求obj2");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized (obj2) {
				System.out.println(Thread.currentThread().getName()+"已经获取到obj1和obj2");
			}
		 }	
		}else {
	     //线程2执行代码 
			  synchronized (obj2) {
					System.out.println(Thread.currentThread().getName()+"已经获取到资源obj2,请求obj1");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					synchronized (obj1) {
						System.out.println(Thread.currentThread().getName()+"已经获取到obj1和obj2");
					}
				 }	
		}
	}

}

测试类:

package cn.yb.thread;

public class DeadLockDemo {

	public static void main(String[] args) {
		//1.创建两个DeadLockRunnable实例:flag = 1;flag = 2
		DeadLockRunnable runnable1 = new DeadLockRunnable(1);
		DeadLockRunnable runnable2 = new DeadLockRunnable(2);
		//2.创建两个线程执行两个DeadLockRunnable
		Thread thread1 = new Thread(runnable1,"runnable1");
		Thread thread2 = new Thread(runnable2,"runnable2");
		thread1.start();
		thread2.start();
		
	}

}

运行结果:

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
更多>相关资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服