zoukankan      html  css  js  c++  java
  • Java线程锁一个简单Lock

    /**
     * @author 
     * 
     * Lock 是java.util.concurrent.locks下提供的java线程锁,作用跟synchronized类似,
     * 单是比它更加面向对象,两个线程执行代码段要实现互斥效果,他们需要用同一个Lock,
     * 锁存在资源类的内部中,而不是存在线程上。
     */
    public class ThreadLock {
        public static void main(String[] args) {
            final Outputer out = new Outputer();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        out.output("duwenlei");
                    }
                }
    
            }).start();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        out.output("shenjing");
                    }
                }
            }).start();
        }
    
    }
    
    class Outputer {
        private Lock lock = new ReentrantLock();
        public void output(String name) {
            lock.lock();
            try {    //这里必须加try,如果程序抛异常后,锁没有及时打开,程序会出异常
                int len = name.length();
                for (int i = 0; i < len; i++) {
                    System.out.print(name.charAt(i));
                }
                System.out.println();
            } finally {
                lock.unlock();
            }
        }
    }
  • 相关阅读:
    简单工厂模式_C#_设计模式
    单例模式_C#设计模式
    快速排序_排序算法_算法
    关于缓存C#
    网络编程的4种IO模型
    一些自己总结
    驱动漏洞中的__try和ProbeForRead
    poj2318
    poj1113
    poj 1904
  • 原文地址:https://www.cnblogs.com/duwenlei/p/5105862.html
Copyright © 2011-2022 走看看