Java learn 死锁

Java learn 死锁,第1张

Java learn 死锁

死锁产生原因:
项目代码比较繁琐,多线程应用里有可能会发生死锁

死锁在数据库里的解释更为清晰全面 且难度也是很大 概念难懂

代码示例死锁:

 class fileguy {
	public static void main(String[] args) {
		players P1=new players("sd",3,3);
		players P2=new players("sd1",2,3);
		
		Thread t1=new Thread()
				{
			public void run()
			{
			try
			{
				
				synchronized(P1)
				{
					System.out.println("占用P1");
				}
				Thread.sleep(1000);
				System.out.println("试图占用P2");
				
			}catch(InterruptedException e)
			{
			e.printStackTrace();	
			}
			System.out.println("t1 等待中 。。。。");
			synchronized (P2) {
				System.out.println("do it?");
			}
			}
				};
				t1.start();
				
				Thread t2=new Thread()
				{
			public void run()
			{
			try
			{
				
				synchronized(P2)
				{
					System.out.println("占用P2");
				}
				Thread.sleep(1000);
				System.out.println("试图占用P1");
				
			}catch(InterruptedException e)
			{
			e.printStackTrace();	
			}
			System.out.println("t2 等待中 。。。。");
			synchronized (P1) {
				System.out.println("do it also?");
			}
			}
				};
				t2.start();
		
		
}
}

  1. 线程1 首先占有对象P1,接着试图占有对象P2
  2. 线程2 首先占有对象P2,接着试图占有对象P1
  3. 线程1 等待线程2释放对象P2
  4. 与此同时,线程2等待线程1释放对象P1
  5. 就这样 两个互相等着 等到…

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5575948.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存