获取synchronized锁中的阻塞队列中的线程是非公平的
Posted 沧海一滴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取synchronized锁中的阻塞队列中的线程是非公平的相关的知识,希望对你有一定的参考价值。
synchronized中阻塞队列的线程是非公平的
测试demo:
import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class SleepState { public static ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); } }; private static final int[] lock = new int[0]; public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(new TestSynchronizedTask(lock, 1000 * 10), "Thread1"); Thread thread2 = new Thread(new TestSynchronizedTask(lock, 10), "Thread2"); Thread thread3 = new Thread(new TestSynchronizedTask(lock, 1000), "Thread3"); thread1.start(); TimeUnit.MILLISECONDS.sleep(1000); thread2.start(); TimeUnit.MILLISECONDS.sleep(1000); thread3.start(); } } class TestSynchronizedTask implements Runnable { private final int[] lock; private int sleepMilliSeconds; public TestSynchronizedTask(int[] lock, int sleepMilliSeconds) { this.lock = lock; this.sleepMilliSeconds = sleepMilliSeconds; } public TestSynchronizedTask(int[] lock) { this(lock, 0); } @Override public void run() { synchronized (lock) { try { System.out.println(MessageFormat.format(" {0} {1} begin", SleepState.threadLocal.get().format(new Date()), Thread.currentThread())); TimeUnit.MILLISECONDS.sleep(sleepMilliSeconds); System.out.println(MessageFormat.format("{0} {1} will end", SleepState.threadLocal.get().format(new Date()), Thread.currentThread())); } catch (InterruptedException e) { e.printStackTrace(); } } } }
执行结果: 2016-05-26 13:31:44.260+0800 Thread[Thread1,5,main] begin 2016-05-26 13:31:54.260+0800 Thread[Thread1,5,main] will end 2016-05-26 13:31:54.260+0800 Thread[Thread3,5,main] begin 2016-05-26 13:31:55.260+0800 Thread[Thread3,5,main] will end 2016-05-26 13:31:55.260+0800 Thread[Thread2,5,main] begin 2016-05-26 13:31:55.276+0800 Thread[Thread2,5,main] will end
以上是关于获取synchronized锁中的阻塞队列中的线程是非公平的的主要内容,如果未能解决你的问题,请参考以下文章