Thread-1.5

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();
}
Thread-1.5_第1张图片
运行结果.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)