public static void main ( String [ ] args ) { final boolean testTimeout = true ; final boolean testDeadlock = false ; final boolean testShutdown = true ; final long timeout = 1000 ; final Object lock1 = new Object ( ) ; final Object lock2 = new Object ( ) ; final Thread thread1 = new Thread ( ) { @ Override public void run ( ) { synchronized ( lock1 ) { System . out . println ( "Thread1 has lock1" ) ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ie ) { ie . printStackTrace ( ) ; } ; synchronized ( lock2 ) { System . out . println ( "Thread1 has both locks" ) ; } } } } ; final Thread thread2 = new Thread ( ) { @ Override public void run ( ) { synchronized ( lock2 ) { System . out . println ( "Thread2 has lock2" ) ; try { Thread . sleep ( 100 ) ; } catch ( InterruptedException ie ) { ie . printStackTrace ( ) ; } ; synchronized ( lock1 ) { System . out . println ( "Thread2 has both locks" ) ; } } } } ; final Thread shutdownThread = new Thread ( ) { @ Override public void run ( ) { System . out . println ( "Shutdown hook sleeping" ) ; try { Thread . sleep ( timeout * 3 ) ; } catch ( InterruptedException ie ) { ie . printStackTrace ( ) ; } finally { System . out . println ( "Shutdown hook finished" ) ; } } } ; final TimedExitThread tet = new TimedExitThread ( ) ; tet . setTimeout ( timeout ) ; if ( testDeadlock ) { thread1 . start ( ) ; thread2 . start ( ) ; } if ( testShutdown ) { Runtime . getRuntime ( ) . addShutdownHook ( shutdownThread ) ; } tet . start ( ) ; if ( testTimeout ) { System . out . println ( "main() sleeping" ) ; try { Thread . sleep ( timeout * 2 ) ; } catch ( InterruptedException ie ) { ie . printStackTrace ( ) ; } finally { System . out . println ( "main() finished" ) ; } } }
Unit test code - run as Java application from your eclipse workspace