「美好,一直在身边」震惊!这样终止线程,竟然会导致服务宕机?( 二 )
// 计数器 int num = 0; @Override public void run { // 同步代码块 , 保证原子操作 synchronized (MyThread.class) { // 自增 num++; try { // 线程休眠 0.1 秒 Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace; } // 自减 num--; System.out.println(Thread.currentThread.getName + " | num=" + num); } } }} 以上程序的执行结果为:
Thread-5 | num=1
Thread-4 | num=1
Thread-2 | num=1
Thread-1 | num=1
Thread-8 | num=1
Thread-6 | num=1
Thread-9 | num=1
Thread-3 | num=1
Thread-7 | num=1
Thread-10 | num=1
从结果可以看出 , 以上代码经过 synchronized 修饰的 ++ 和 -- 操作 , 到最后打印的结果 num 竟然不是 0 , 而是 1 。
这是因为 stop 方法会释放此线程中的所有锁 , 导致程序执行紊乱 , 破坏了程序的原子操作逻辑 。
以上的这些问题 , 导致了 JDK 废弃了 stop 的方法 , 它的废弃源码如下: /** * Forces the thread to stop executing. * * If there is a security manager installed, its checkAccess * method is called with this * as its argument. This may result in a * SecurityException being raised (in the current thread). * * If this thread is different from the current thread (that is, the current * thread is trying to stop a thread other than itself), the * security manager's checkPermission method (with a * RuntimePermission("stopThread") argument) is called in * addition. * Again, this may result in throwing a * SecurityException (in the current thread). * * The thread represented by this thread is forced to stop whatever * it is doing abnormally and to throw a newly created * ThreadDeath object as an exception. * * It is permitted to stop a thread that has not yet been started. * If the thread is eventually started, it immediately terminates. * * An application should not normally try to catch * ThreadDeath unless it must do some extraordinary * cleanup operation (note that the throwing of * ThreadDeath causes finally clauses of * try statements to be executed before the thread * officially dies). If a catch clause catches a * ThreadDeath object, it is important to rethrow the * object so that the thread actually dies. * * The top-level error handler that reacts to otherwise uncaught
推荐阅读
- @选择一款5G手机,回到美好生活,天猫“418”大促正是个好时机!
- 【美好,一直在身边】加快工业互联网与制造业融合,遂宁开启工业互联网时代→
- 『美好,一直在身边』新能源新项目!长虹控股投资近20亿元锂电池项目在绵阳开工
- 美好,一直在身边@微信小程序增加跨境电商服务类目
- 「美好,一直在身边」马鞍形 星空顶 杭州地铁5号线的这个入口很特别
- 美好,一直在身边@电子城转向新型科技服务业务显成效 科技服务收入占比持续增加
- 美好,一直在身边■购物社交平台首推“人品评级”,未来已来
- 『美好,一直在身边』37家公司市值超百亿,科创板造富效应显著,会一直火下去么?
- 『Google Play』一直说的订阅政策更新来了 6月16日是最后期限
- 美好,一直在身边■2020年第12批CDN牌照下发:全国CDN经营资质企业突破200家
