(^^)/デッドロックの簡単な例

2867 ワード

スレッドクラス:
import java.util.concurrent.locks.ReentrantLock;


public class DeadLockCar extends Thread {
	private Object obj;
	static ReentrantLock forward = new ReentrantLock();
	static ReentrantLock backword = new ReentrantLock();
	
	public DeadLockCar(Object obj){
		this.obj = obj;
	}
	
	public void run(){
		if(obj==forward){
			try {
				forward.lockInterruptibly();
				Thread.sleep(1000);
				backword.lockInterruptibly();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				if(forward.isHeldByCurrentThread()){
					forward.unlock();
				}
				if(backword.isHeldByCurrentThread()){
					backword.unlock();
				}
			}
			
		}else{
			try {
				backword.lockInterruptibly();
				Thread.sleep(1000);
				forward.lockInterruptibly();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				if(backword.isHeldByCurrentThread()){
					backword.unlock();
				}
				if(forward.isHeldByCurrentThread()){
					forward.unlock();
				}
			}
		}
	}
	
	
	public static void main(String[] args) {
		Thread c1 = new DeadLockCar(DeadLockCar.forward);
		Thread c2 = new DeadLockCar(DeadLockCar.backword);
		c1.start();
		c2.start();
	}
}

 
 
 
2つのスレッドクラス:
public class DeadLock{
	public static void main(String[] args) {
		Object obj1 = new Object();
		Object obj2 = new Object();
		Thread t1 = new LockA(obj1,obj2);
		Thread t2 = new LockB(obj1,obj2);
		t1.start();
		t2.start();
	}
}

class LockA extends Thread {
	private Object obj1;
	private Object obj2;
	public LockA(Object obj1,Object obj2){
		this.obj1 = obj1;
		this.obj2 = obj2;
	}
	
	public void run(){
		synchronized(obj1){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized(obj2){
				System.out.println("Lock A");
			}
		}
	}
}

class LockB extends Thread {
	private Object obj1;
	private Object obj2;
	public LockB(Object obj1,Object obj2){
		this.obj1 = obj1;
		this.obj2 = obj2;
	}
	
	public void run(){
		synchronized(obj2){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			synchronized(obj1){
				System.out.println("Lock B");
			}
		}
	}
}