多线程四:可重入锁

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dancheng1/article/details/80984843

自己可以再次获取自己的内部锁。比如有1调线程获得了某个对象的锁,此时这个对象锁还没有释放,当其再次想要获取这个对象的锁的时候还是可以获取的,如果不可锁重入的话,就会造成死锁。可重入锁也支持在父类继承的环境中。(即子类锁中调用了父类带锁函数)

 

普通可重入锁示例代码:

public class Service {
	synchronized public void service1() {
		System.out.println(Thread.currentThread().getName() + " ---service1");
		service2();
	}
	
	synchronized public void service2() {
		System.out.println(Thread.currentThread().getName() + " ---service2");
		service3();
	}
	
	synchronized public void service3() {
		System.out.println(Thread.currentThread().getName() + " ---service3");
	}
}

public class MyThread extends Thread {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		Service service = new Service();
		service.service1();
	}
}

public class Run {
	public static void main(String[] args) {
		MyThread t = new MyThread();
		t.setName("A");
		t.start();
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		MyThread t1 = new MyThread();
		t1.setName("B");
		t1.start();
	}
}

运行结果:


父类继承当中的可重入锁:

public class Main {
	public int i = 10;
	synchronized public void operateMainMethod() {
		try {
			i--;
			System.out.println("main print i=" + i);
			Thread.sleep(100);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class Sub extends Main {
	synchronized public void operateISubMethod() {
		try {
			while(i > 0) {
				i--;
				System.out.println("sub print i=" + i);
				Thread.sleep(100);
				this.operateMainMethod();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class MyThread extends Thread {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		Sub sub = new Sub();
		sub.operateISubMethod();
	}
}

public class Run {
	public static void main(String[] args) {
		MyThread thread = new MyThread();
		thread.start();
	}
}

运行结果:


阅读更多
换一批

没有更多推荐了,返回首页