Java模拟Thread线程死锁

package com.thread.test;

public class DeadLockTest implements Runnable{

	public int flag=1;
	static Object obj1=new Object(),obj2=new Object();
	@Override
	public void run() {
		System.out.println(flag);
		
		if(flag==1){
			synchronized (obj1) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (obj2) {
					System.out.println("obj2");
				}
			}
		}
		
		if(flag==0){
			synchronized (obj2) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				synchronized (obj1) {
					System.out.println("obj1");
				}
			}
		}
	}
	
	public static void main(String[] args) {
		DeadLockTest d1=new DeadLockTest();
		DeadLockTest d2=new DeadLockTest();
		d1.flag=1;
		d1.flag=0;
		Thread t1=new Thread(d1);
		Thread t2=new Thread(d2);
		t1.start();
		t2.start();
	}
}

你可能感兴趣的:(thread)