java写一个死锁

package thread.deadlock;
/**
 * 一个死锁
 * @author zzh
 *
 */
public class DeadLock {

	public static void main(String[] args) {
		Test test = new Test(true);
		Test test_2 = new Test(false);
		
		Thread t1 = new Thread(test);
		Thread t2 = new Thread(test_2);
		
		t1.start();
		t2.start();
		
	}

}

class MyLock{
	public static final Object locka = new Object(); 
	public static final Object lockb = new Object(); 
}

class Test implements Runnable{
	private boolean flag;
	
	Test(boolean flag){
		this.flag = flag;
	}
	
	@Override
	public void run() {
		if(flag){
			while (true) {
				synchronized (MyLock.locka) {
					System.out.println("if......locka...");
					synchronized (MyLock.lockb) {
						System.out.println("if......lockb...");

					}
				}
			}
		}else{
			while (true) {
				synchronized (MyLock.lockb) {
					System.out.println("else......lockb...");
					synchronized (MyLock.locka) {
						System.out.println("else......locka...");

					}
				}
			}
		}
		
	}
	
}


你可能感兴趣的:(java,多线程)