手写一个死锁程序

package DeadLock;
/*写一个两个线程死锁的程序
 * coded by Jerome
 */
class MyDeadLock implements Runnable{
	boolean flag;
	static Object o1 = new Object();
	static Object o2 = new Object();
	public MyDeadLock(boolean flag){
		this.flag = flag;
	}
	public void run(){
		if(this.flag){
			synchronized (o1) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				synchronized (o2) {
					System.out.println("我没发生死锁");
					
				}
			}
		}
		else{
			synchronized (o2) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				synchronized (o1) {
					System.out.println("我也是");
				}
				
			}
		}
	}
}
public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread t1 = new Thread(new MyDeadLock(true));
		Thread t2 = new Thread(new MyDeadLock(false));
		t1.start();
		t2.start();

	}

}

控制台什么也没有显示,说明该程序发生了死锁

猜你喜欢

转载自blog.csdn.net/caisongcheng_good/article/details/80561642