synchronized,CountDownLatch理解

来源:互联网 发布:钢琴软件电脑版 编辑:程序博客网 时间:2024/05/18 22:10

1.不管synchronized是用来修饰方法,还是修饰代码块,其本质都是锁定某一个对象。修饰方法时,锁上的是调用这个方法的对象,即this;修饰代码块时,锁上的是括号里的那个对象

在上面的代码中,很明显就是锁定的MyTask对象本身。但是由于在每一个线程中,MyTask对象都是独立的,这就导致实际上每个线程都对自己的MyTask进行锁定,而并不会干涉其它线程的MyTask对象。换言之,上锁压根没有意义


2.

CountDownLatch是通过“共享锁”实现的。在创建CountDownLatch中时,会传递一个int类型参数count,该参数是“锁计数器”的初始状态,表示该“共享锁”最多能被count给线程同时获取。当某线程调用该CountDownLatch对象的await()方法时,该线程会等待“共享锁”可用时,才能获取“共享锁”进而继续运行。而“共享锁”可用的条件,就是“锁计数器”的值为0!而“锁计数器”的初始值为count,每当一个线程调用该CountDownLatch对象的countDown()方法时,才将“锁计数器”-1;通过这种方式,必须有count个线程调用countDown()之后,“锁计数器”才为0,而前面提到的等待线程才能继续运行!

CountDownLatch的两个主要方法

// 使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断。void await()
// 递减锁存器的计数,如果计数到达零,则释放所有等待的线程。void countDown()

private static Hashtable<String, String> hashtable = new Hashtable<String, String>();private static CountDownLatch latch = new CountDownLatch(1);public static void main(String[] args) throws InterruptedException {    HashTableTest hashTableTest = new HashTableTest();    Thread tt = new Thread(hashTableTest);    tt.start();    latch.await(); 若不添加latch关键字取出的值为null 主线程调用 latch.await时,除非latch状态值为0,否则会一直阻塞休眠。当所有任务执行完后,主线程唤醒,最终执行打印动作。    System.out.println(hashtable.get("1"));}@Overridepublic void run() {    for (int i = 0; i < 10; i++) {        System.out.println("-----" + i);        hashtable.put(Integer.toString(i), Integer.toString(i));    }    latch.countDown();}

0 0
原创粉丝点击