「美好,一直在身边」震惊!这样终止线程,竟然会导致服务宕机?( 二 )

// 计数器 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


推荐阅读