死锁是在多线程情况下最严重的问题,在多线程对公共资源(文件,数据)等进行操作时,彼此不释放自己的资源,而去试图操作其他线程的资源,而形成的交叉引用,就会产生死锁。
假如我有一个需求,有一个线程,先写入A文件,在顺序写入B文件,再保存起来。还有另一个线程,先写入B文件,再顺序写入A文件,再保存起来。代码如下:
private static String fileA = "A文件";
private static String filedB = "B文件";
public static void main(String[] args) {
new Thread() { //线程1
//重写run方法
public void run() {
while (true) {
synchronized (fileA) {//打开文件A,线程独占fileA
System.out.println(this.getName() + ":文件A写入");
synchronized (filedB) {
System.out.println(this.getName() + ":文件B写入");
}
System.out.println(this.getName() + ":所有文件保存");
}
}
}
}.start();
new Thread() { //线程2
//重写run方法
public void run() {
while (true) {