并发包java.util.concurrent.locks.Lock

**
 * 
 * @描述: Lock比传统线程模型中的synchronized方式更加面向对象、与生活中的锁类似,锁本身也应该是一个对象,两个线程执行的代码片段要实现同步互排的效果
 *        它们必须用同一个LOCK,锁是上线代表要操作的资源内部类的内部方法上,而不是线程的方法中 .
 * @作者: Wnj .
 * @创建时间: 2017年5月16日 .
 * @版本: 1.0 .
 */
public class LockTest {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        new LockTest().init();
    }
    
    private void init() {
        final Outputer outputer = new Outputer();
        
        //A
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //如果A线程还没打印完成,B线程就被调度执行,那么打印就不完整
                    outputer.output("zhangxiaoxiang");
                }
                
            }
        }).start();
        
        //B
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(10);
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    outputer.output("lihuoming");
                }
                
            }
        }).start();
        
    }
    
    /**
     * 
     * @描述: 锁是上线代表要操作的资源内部类的内部方法上
     * @作者: Wnj .
     * @创建时间: 2017年5月16日 .
     * @版本: 1.0 .
     */
    static class Outputer {
        
        Lock lock = new ReentrantLock();
        
        /**
         * 使用lock
         * <功能详细描述>
         * @param name
         */
        public void output(String name) {
            int len = name.length();
            lock.lock();
            try {
                for (int i = 0; i < len; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            }
            finally {
                lock.unlock();
            }
        }
        /**
         * 使用synchronized
         * <功能详细描述>
         * @param name
         */
        public synchronized void output2(String name) {
            int len = name.length();
            for (int i = 0; i < len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
        /**
         * 使用synchronized
         * <功能详细描述>
         * @param name
         */
        public static synchronized void output3(String name) {
            int len = name.length();
            for (int i = 0; i < len; i++) {
                System.out.print(name.charAt(i));
            }
            System.out.println();
        }
    }
}

 

posted @ 2017-05-25 10:20  superGG  阅读(233)  评论(0编辑  收藏  举报