---
title: "编写一个程序使两个线程陷入死锁"
author: "hy2012_campus"
date: "2014-12-23T14:21:30Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-12-23T14:21:30Z"
id: 2169513
url: "https://hy2012.iteye.com/blog/2169513"
---

来源于：http://thecodesample.com/?p=710 进去看看吧 一定会有收获的，搬砖到此只是为了收集起来，免得主任删除等操作。

```
public class DeadlockExample {
	String resource1 = "资源1";
	String resource2 = "资源2";
	Thread t1 = new Thread("线程1") {
		public void run() {
			while (true) {
				synchronized (resource1) {
					synchronized (resource2) {
						System.out.printf("线程1拥有[%s], 需要[%s]\n", resource1, resource2);
					}
				}
			}
		}
	};
	Thread t2 = new Thread("线程2") {
		public void run() {
			while (true) {
				synchronized (resource2) {
					synchronized (resource1) {
						System.out.printf("线程2拥有[%s], 需要[%s]\n", resource2, resource1);
					}
				}
			}
		}
	};
	public static void main(String a[]) {
		DeadlockExample test = new DeadlockExample();
		test.t1.start();
		test.t2.start();
	}
}
```