为什么Thread.stop会过期?一段引起同步异常问题的代码样例

package thread;

/**
 * Thread.stop引起同步异常问题的代码样例。<br>
 * 所以过期且不推荐使用。他会造成数据的不一致问题,引起垃圾数据。
 *
 * @author Administrator
 *
 */
public class ThreadStopTest {
     private static Object lock = new Object();
     private static int number = 0;
     private static String name = "Name0";


     public static void main(String[] args) {
        ThreadStop t = new ThreadStop();
        t.start();
        ThreadRun t2 = new ThreadRun();
        t2.start();
         // 输出为
         // number=1
         // name=Name0,
         // 如果去掉stop,则输出正常为
         // nunber=1
         // name=Name11
        t.stop();
    }


     static class ThreadRun extends Thread {
         public void run() {
             synchronized (lock) {
                 try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println( "number=" + number);
                System.out.println( "name=" + name);
            }
        }
    }


     static class ThreadStop extends Thread {
         public void run() {
             synchronized (lock) {
                number++;
                 try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                name = "Name" + number;
            }


        }
    }
}


/*Why is Thread.stop deprecated?
  为什么Thread.stop会过期?
  Because it is inherently unsafe. Stopping a thread causes it to unlock
  all the monitors that it has locked. (The monitors are unlocked as the
  ThreadDeath exception propagates up the stack.) If any of the objects
  previously protected by these monitors were in an inconsistent state,
  other threads may now view these objects in an inconsistent state.
  Such objects are said to be damaged. When threads operate on damaged
  objects, arbitrary behavior can result. This behavior may be subtle
  and difficult to detect, or it may be pronounced. Unlike other
  unchecked exceptions, ThreadDeath kills threads silently; thus, the
  user has no warning that his program may be corrupted. The corruption
  can manifest itself at any time after the actual damage occurs, even
  hours or days in the future.
  因为它本身就是不安全的。停止一个线程引起它释放了它所有的锁的监控。(死亡线程的被锁的
  监控上的异常在堆栈传播)。如有任何以前被这些所锁保护的对象将处于不一致的状态,其他线
  程现在可以看到不一致的状态。这类对象可以认定是被破坏的。当线程操作被破坏的对象时,可
  能引发任何结果。此现象可能是微妙和难以察觉,也可以显着。不同于其他为检查的例外,
  ThreadDeath悄悄地杀死线程,因此,用户没有收到任何警告,他的程序可能会损坏。问题可
  以出现在任何时间后,实际损害发生,甚至在数小时或数天以后。
*/

你可能感兴趣的:(代码,职场,休闲,Thread.stop)