The thread that blocks the queue in synchronized is unfair
Test Demo:
ImportJava.text.MessageFormat;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.concurrent.TimeUnit; Public classSleepstate { Public StaticThreadlocal<simpledateformat> ThreadLocal =NewThreadlocal<simpledateformat>() {@OverrideprotectedSimpleDateFormat InitialValue () {return NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss. Sssz "); } }; Private Static Final int[] lock =New int[0]; Public Static voidMain (string[] args)throwsinterruptedexception {Thread thread1=NewThread (NewTestsynchronizedtask (lock, + *), "Thread1"); Thread thread2=NewThread (NewTestsynchronizedtask (lock, Ten), "Thread2"); Thread thread3=NewThread (NewTestsynchronizedtask (lock, +), "Thread3"); Thread1.start (); TimeUnit.MILLISECONDS.sleep (1000); Thread2.start (); TimeUnit.MILLISECONDS.sleep (1000); Thread3.start (); }}classTestsynchronizedtaskImplementsRunnable {Private Final int[] lock; Private intSleepmilliseconds; PublicTestsynchronizedtask (int[] Lock,intsleepmilliseconds) { This. Lock =lock; This. Sleepmilliseconds =Sleepmilliseconds; } PublicTestsynchronizedtask (int[] Lock) { This(Lock, 0); } @Override Public voidrun () {synchronized(lock) {Try{System.out.println (Messageformat.format ("{0} {1} begin", SleepState.threadLocal.get (). Format (NewDate ()), Thread.CurrentThread ())); TimeUnit.MILLISECONDS.sleep (Sleepmilliseconds); System.out.println (Messageformat.format ("{0} {1} would end", SleepState.threadLocal.get (). Format (NewDate ()), Thread.CurrentThread ())); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
2016-05-26 13:31:44.260+0800 thread[thread1,5, main] begin2016-05-26 13:31:54.260+0800 Thread[thread1, 5, main] 2016-05-26 13:31:54.260+0800 thread[Thread3, 5, main] begin2016-05-26 13:31:55.260+0800 thread[Thread3, 5, main] 2016-05-26 13:31:55.260+0800 thread[thread2,5 , main] Begin2016-05-26 13:31:55.276+0800 Thread[thread2,5,main] 'll end
Getting a thread in a blocking queue in a synchronized lock is unfair