线程死锁问题

package com.yaspeed.threadnotice;

/**
 * 测试线程死锁问题
 * 问题分析:线程死锁的原因线程之间所需要的资源被对方占有不释放导致
 * 例如:线程A有资源A1,线程B有资源B1,现在线程A占有A1的情况下,需要资源B1,
 * 线程B占有B1的情况下需要A1,最终导致死锁的产生
 * @author wd
 */

public class TestDeathLock {
	
	static StringBuffer sb1 = new StringBuffer();
	static StringBuffer sb2 = new StringBuffer();
	
	static class Thread1 implements Runnable{
		public void run(){
			synchronized(sb1){
				sb1.append("A");
				synchronized(sb2){
					sb2.append("B");
					System.out.println(sb1.toString());
					System.out.println(sb2.toString());
				}
			}
		}
	}
	
	static class Thread2 implements Runnable{
		public void run(){
			synchronized(sb2){
				sb2.append("C");
				synchronized(sb1){
					sb1.append("D");
					System.out.println(sb1.toString());
					System.out.println(sb2.toString());
				}
			}
		}
	}
	
	public static void main(String[] args) {
		
		Thread1 t1 = new TestDeathLock.Thread1();
		Thread2 t2 = new TestDeathLock.Thread2();
		Thread th1 = new Thread(t1);
		Thread th2 = new Thread(t2);
		th1.start();th2.start();
		
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值