zoukankan      html  css  js  c++  java
  • 多线程篇八:线程锁

    1.线程锁Lock/ReentrantLock

    package com.test.lock;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    //线程锁,通常用于替换synchronized,比synchronized更加面向对象
    public class LockTest {
        static class Outputer{
            Lock locks=new ReentrantLock();
            //方法1
            public void output1(String name){
                int len=name.length();
                locks.lock();//确保完整输出chenxiaobing后再输出donyanxia
                try{
                    for(int i=0;i<len;i++){
                        System.out.print(name.charAt(i));
                    }
                    System.out.println();
                }finally{
                    locks.unlock();//避免执行的代码发送异常,导致死锁,因此需要使用finally,无论执行是否成功,都进行解锁
                }
            }
        }
        public void init(){
            final Outputer o=new Outputer();
            
            //线程1
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        o.output1("chenxiaobing");
                    }
                }
            }).start();
            
            //线程2
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        o.output1("donyanxia");
                    }
                }
            }).start();
        }
        public static void main(String[] args) {
            new LockTest().init();
            //交替输出chenxiaobing、donyanxia
        }
    }
    View Code
  • 相关阅读:
    iOS 接入 招商 一网通的 各种坑
    2016证书无效,看这里
    iOS-响应上下左右滑动手势
    在线HTTP POST/GET接口测试工具
    iOS开发中使用宏定义提高开发效率
    iOS宏定义的使用与规范
    Swift
    koa 第一课
    angular directive的使用
    angular的service服务eg:value,constant,factory,service
  • 原文地址:https://www.cnblogs.com/brant/p/6028553.html
Copyright © 2011-2022 走看看