死鎖代碼

標誌位未釋放造成的死鎖

public class Utils {
    private static Logger logger = LoggerFactory.getLogger(Utils.class);
    public static boolean used=false;
    public synchronized static void work(){
        if(!used){
            try {
                logger.info("work start");
                used=true;
                Thread.sleep(3000);
                System.out.println(0/0);
//                used=false;
                logger.info("work end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            logger.info("資源正在使用中");
        }

    }


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    work();
                }
            });
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章