多线程(五)线程的5种状态以及死锁_死锁

  • –阻塞
    • –I/O: 可能线程在进行一个大数据的I/O操作, 导致程序看上去假死,导致的阻塞
    • –sleep(): 线程处于休眠状态
    • –lock: 等待锁资源的时候
    • –yield: 主动将CPU时间片释放
      多线程(五)线程的5种状态以及死锁_java_02

–死锁案例

package com.ygq.thread;

/**
 * @author :GQ.Yin
 * @date :Created in 2019/7/21 20:46
 * @description:死锁案例
 * @version: $version$
 */
public class DeadLock {
    private static String fileA = "A文件";
    private static String fileB = "B文件";

    public static void main(String[] args) {

        //任务1
        new Thread(){
            public void run(){
                while (true){
                    synchronized (fileA) { //打开文件A线程独占
                        System.out.println(this.getName() + ":文件A写入");
                        synchronized (fileB){//打开文件B线程独占
                            System.out.println(this.getName() + ":文件B写入");
                        }
                        System.out.println(this.getName() + "所有文件保存");
                    }
                }
            }
        }.start();


        //任务2
        new Thread(){
            public void run(){
                while (true){
                    synchronized (fileB) { //打开文件B线程独占
                        System.out.println(this.getName() + ":文件B写入");
                        synchronized (fileA){//打开文件A线程独占
                            System.out.println(this.getName() + ":文件A写入");
                        }
                        System.out.println(this.getName() + "所有文件保存");
                    }
                }
            }
        }.start();
    }
}