java之多线程死锁

java死锁方面的知识也是在面试过程中经常被提及的,以下是关于死锁的一个实例:

package com.java.Test;

public class DeadLock extends Thread {
	Tom t = new Tom();
	Kite k = new Kite();
	DeadLock(){
		this.start();
		k.lend(t);
	}
	public void run()
	{
		t.lend(k);
	}
	
	public static void main(String[] args) {
		new DeadLock();
	}
}

class Kite
{
	public synchronized void lend(Tom t)
	{
	 System.out.println("我是否应该借筷子给tom");
	 try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	 t.eat();
	}
	
	public synchronized void eat(){
		System.out.println("Kite可以吃饭了");
	}
}

class Tom
{
	public synchronized void lend(Kite k)
	{
	 System.out.println("我是否应该借筷子给Kite");
	 try {
		Thread.sleep(1000);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	 k.eat();
	}
	
	public synchronized void eat(){
		System.out.println("Tom可以吃饭了");
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_37224686/article/details/61655407