美文网首页
Thread-1.5

Thread-1.5

作者: MangoDai | 来源:发表于2017-08-16 15:24 被阅读0次

Lock

Java1.5以后添加了Lock类,可以锁定代码,相当于synchronized .

 /** {@code Lock} implementations provide more extensive locking
 * operations than can be obtained using {@code synchronized} methods
 * and statements.  They allow more flexible structuring, may have
 * quite different properties, and may support multiple associated
 * {@link Condition} objects.
 **/
public static void out(String str) {
     int len = str.length();
//    lock.lock();
     for (int i = 0; i < len; i++) {
           System.out.print(str.charAt(i));
     }
    System.out.println();
}
运行结果.png

当我们锁上之后

    static class Output {
        static Lock lock = new ReentrantLock();
        public static void out(String str) {
            int len = str.length();
            lock.lock();
            try {
                for (int i = 0; i < len; i++) {
                    System.out.print(str.charAt(i));
                }
            } catch (Exception e) {
            }finally {
                lock.unlock();
            }
            System.out.println();
        }
    }

相关文章

  • Thread-1.5

    Lock Java1.5以后添加了Lock类,可以锁定代码,相当于synchronized . 当我们锁上之后

网友评论

      本文标题:Thread-1.5

      本文链接:https://www.haomeiwen.com/subject/mcvirxtx.html