博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
获取synchronized锁中的阻塞队列中的线程是非公平的
阅读量:5892 次
发布时间:2019-06-19

本文共 2280 字,大约阅读时间需要 7 分钟。

 

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
threadLocal = new ThreadLocal
() { @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]  begin2016-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]  begin2016-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]  begin2016-05-26 13:31:55.276+0800 Thread[Thread2,5,main]  will end

 

转载于:https://www.cnblogs.com/softidea/p/5530798.html

你可能感兴趣的文章