He can block threads anywhere in the thread, Locksupport's static Method Park () can block the current thread, similar to Parknanos () Parkuntil (), and so on, they implement a time-limited wait
Public classLocksupportdemo { Public StaticObject U =NewObject (); StaticChangeobjectthread T1 =NewChangeobjectthread ("T1"); StaticChangeobjectthread t2 =NewChangeobjectthread ("T2"); Public Static classChangeobjectthreadextendsThread { PublicChangeobjectthread (String name) {Super. SetName (name); } Public voidrun () {synchronized(U) {System.out.println ("In" +getName ()); Locksupport.park (); } } } Public Static voidMain (string[] args)throwsinterruptedexception {t1.start (); Thread.Sleep (100); T2.start (); Locksupport.unpark (t1); Locksupport.unpark (T2); T1.join (); T2.join (); }}
We can use the park () and Unpark () methods to replace the previous suspend () and resume () methods. Of course, we still can't guarantee that the Unpark () method happens after park (0, when you execute this code, you'll see that it ends up all the time. , it does not cause the thread to hang permanently because of the park () method, because the Locksupport class uses a similar semaphore mechanism, and he prepares a license for each thread. This feature enables: even if the Unpark () operation occurs before Park (), It also enables the next park () operation to return immediately. This is the main reason why the above code can be successfully ended. Out of the function of timed blocking, but also support the interrupt effect, but unlike other receive interrupt function, he will not throw interruptedexception exception, he will only silently return, but we can get the interrupt token from thread.interrupted () and other methods.
Public classLocksupportintdemo { Public StaticObject U =NewObject (); StaticChangeobjectthread T1 =NewChangeobjectthread ("T1"); StaticChangeobjectthread t2 =NewChangeobjectthread ("T2"); Public Static classChangeobjectthreadextendsThread { PublicChangeobjectthread (String name) {Super. SetName (name); } Public voidrun () {synchronized(U) {System.out.println ("In" +getName ()); Locksupport.park (); if(thread.interrupted ()) {System.out.println (GetName () )+ "was interrupted!"); }} System.out.println (GetName ()+ "Execution End"); } } Public Static voidMain (string[] args)throwsinterruptedexception {t1.start (); Thread.Sleep (100); T2.start (); T1.interrupt (); Locksupport.unpark (T2); }}
Thread blocking Tool class: Locksupport (Reading notes)