zoukankan      html  css  js  c++  java
  • 获取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
  • 相关阅读:
    关于applet
    Hello.java
    filter用户授权的例子
    logfilter
    Java EE课程设计——企业人力资源管理系统
    条件查询、SQL、JPQL、HQL比较
    web service和ejb的区别
    RPC
    hashcode()和equals()的区别
    关于JSON
  • 原文地址:https://www.cnblogs.com/softidea/p/5530798.html
Copyright © 2011-2022 走看看