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

在这里插入图片描述

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

–死锁案例

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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值