Java高并发编程学习--10. synchronized的缺陷

一、synchronized的缺陷测试代码

package communication;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName SynchronizedDefect
 * @Description TODO
 * synchronized的缺陷:
 * 1. 无法控制阻塞的时长
 * 2. 阻塞不可被中断
 * @Author Cays
 * @Date 2019/3/14 8:40
 * @Version 1.0
 **/
public class SynchronizedDefect {
    public synchronized void syncMethod(){
        try {
            System.out.println(Thread.currentThread().getName()+" start.");
            TimeUnit.HOURS.sleep(1);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }
    public static void main(String []args) throws InterruptedException {
        SynchronizedDefect defect=new SynchronizedDefect();
        Thread t1=new Thread(defect::syncMethod,"T1");
        t1.start();
        //t1的synchrozied的时长无法控制
        //synchrozied无法被中断
        TimeUnit.MILLISECONDS.sleep(2);
        Thread t2=new Thread(defect::syncMethod,"T2");
        t2.start();
        //尝试打断t2线程
        t2.interrupt();
        System.out.println("T2 interrupt:"+t2.isInterrupted());
        System.out.println("T2 status:"+t2.getState());
    }
}

二、运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_39400984/article/details/89786070