We know that multiple threads in the same process share process resources, including main memory, file handles, lock resources, and so on. Then, when a thread dies (an abnormal exit, a dead loop, etc.), it causes the thread to never be freed of its resources, which affects the normal work of other threads, as shown in the following example.
1 ImportJava.util.concurrent.locks.Lock;2 ImportJava.util.concurrent.locks.ReentrantLock;3 4 Public classExceptinchildthread {5 Public Static voidMain (string[] args) {6 7Lock lock=NewReentrantlock (true);8Runnable taskruntimeexcept=NewRunnable () {9 @OverrideTen Public voidrun () { One Lock.lock (); A int[] Array =New int[2]; -System.out.println (array[2]); - Lock.unlock (); the } - }; -Thread threadruntimeexcept =NewThread (taskruntimeexcept); - Threadruntimeexcept.start (); + - NewThread (NewRunnable () { + @Override A Public voidrun () { at for(inti = 0; I < 100; i++) { - Lock.lock (); - System.out.println (i); - Lock.unlock (); - } - } in }). Start (); - } to}
Output:
Exception in Thread "Thread-0" Java.lang.arrayindexoutofboundsexception:2at Edu.whu.swe.lxl.learn.except.exceptinchildthread$1.run (exceptinchildthread.java:15) at Java.lang.Thread.run ( thread.java:748)
As you can see, the second thread has not been executed. The reasons are as follows:
After the first thread threadruntimeexcept an array out of bounds, the thread exception is not caught, causing the thread to exit unexpectedly. However, the exception of a child thread is not passed to the main thread (Runable's Run method has no throw), so the main thread can still be run. The problem is that threadruntimeexcept this thread takes possession of lock, and exits unexpectedly before the lock is released, the lock is always occupied until the second thread tries to acquire the lock, and it blocks there.
The consequences of a thread dying in a process